在使用宏(xlsm)将数据导出到Excel工作簿后,我运行宏,然后删除宏,以便将工作簿保存为xlsx。为了删除宏,我打开xlsm as zip存档(通过C#ZipFile类),删除条目“xl/vbaProject.bin”,并删除“xl/#rels/workbook.xml.rels”中的关系。然后我将文件从xlsm重命名为xlsx。到目前为止,这很好,但是当我在Excel中打开xlsx文件时,我得到“Excel无法打开该文件,因为文件格式或文件扩展名无效。请验证文件是否已损坏,以及文件扩展名是否与文件格式匹配,以便完全删除工作簿中的vba代码。有人能帮我吗?
const string vbaProjectEntryName = "xl/vbaProject.bin"; // Contains the VBA code
const string relationsEntryName = "xl/_rels/workbook.xml.rels"; // Relation/Link to the vba project
using (var zip = ZipFile.Open(fileName, ZipArchiveMode.Update))
{
var entry = zip.GetEntry(vbaProjectEntryName);
if (entry != null)
{
entry.Delete();
entry = zip.GetEntry(relationsEntryName);
if (entry != null)
{
var contents = string.Empty;
using (var streamReader = new StreamReader(entry.Open()))
{
contents = streamReader.ReadToEnd();
}
var relationText = "<Relationship Id=\"rId6\" Type=\"http://schemas.microsoft.com/office/2006/relationships/vbaProject\" Target=\"vbaProject.bin\"/>";
contents = contents.Replace(relationText, string.Empty);
entry.Delete();
entry = zip.CreateEntry(relationsEntryName);
using (var streamWriter = new StreamWriter(entry.Open()))
{
streamWriter.Write(contents);
}
}
}
}