将数据导出到带有宏(xlsm)的Excel工作簿中之后,我运行该宏,然后删除该宏,以便能够将工作簿另存为xlsx。为了删除宏,我将xlsm作为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);
}
}
}
}