在 Interop.Excel 中使用 workbook.SaveAs() 将 .xslm 转换为 .xslx,执行没有问题,但不保存文件
Interop.Excel 版本 12
Office Excel 2007
我编写了打开 .xslm 文件的代码,然后将其转换(保存)为 .xslx。在这之间,我确实需要做一些处理,但这并不重要。以下是代码:
namespace Exceltest
{
class Program
{
static void Main(string[] args)
{
Application oXL = null;
oXL = new Application();
oXL.Visible = false;
oXL.DisplayAlerts = false;
try
{
Workbook book = oXL.Workbooks.Open("E:\\CorrectPF1.xlsm", 0, true, 5, "access123", "", true,
XlPlatform.xlWindows, "\t", false, false, 0, true, null, XlCorruptLoad.xlNormalLoad);
Worksheet worksheet = (Worksheet)book.Sheets["Resource allocation"];
worksheet.Activate();
oXL.Visible = false;
oXL.DisplayAlerts = false;
book.SaveAs("E:\\PF1.xlsx", XlFileFormat.xlOpenXMLWorkbook,
"", Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing,
Type.Missing, false);
}
catch (Exception ex)
{
//Handling exception here
}
}
}
}
该代码执行时没有问题(没有任何异常),但没有保存带有 .xslx 扩展名的文件。我发现它适用于某些文件集,但不适用于其他文件集。比如说,它不适用于名为 PF1.xslm 的文件。我可以在 Office Excel 中打开 PF1.xslm 并将其另存为 .xslx。因此,同样的假设也可以以编程方式工作。
Interop.Excel version 12
Office Excel 2007
I have worked on code to open .xslm file and then converting (saving) it as .xslx. Between this, I do need to do some processing as well but it doesn't matter. Following is the code:
namespace Exceltest
{
class Program
{
static void Main(string[] args)
{
Application oXL = null;
oXL = new Application();
oXL.Visible = false;
oXL.DisplayAlerts = false;
try
{
Workbook book = oXL.Workbooks.Open("E:\\CorrectPF1.xlsm", 0, true, 5, "access123", "", true,
XlPlatform.xlWindows, "\t", false, false, 0, true, null, XlCorruptLoad.xlNormalLoad);
Worksheet worksheet = (Worksheet)book.Sheets["Resource allocation"];
worksheet.Activate();
oXL.Visible = false;
oXL.DisplayAlerts = false;
book.SaveAs("E:\\PF1.xlsx", XlFileFormat.xlOpenXMLWorkbook,
"", Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing,
Type.Missing, false);
}
catch (Exception ex)
{
//Handling exception here
}
}
}
}
This code executes with no issue (without any exception) but No file is saved with .xslx extension. I found it is working for some set of files but not others. Say, it is not working for file named PF1.xslm. I am able to open PF1.xslm in Office Excel and save it as .xslx. So, the same suppose to work programmatically as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将包含宏的文件保存为 .xlsx 格式。如果您自己保存文件,您应该会收到一条错误消息。我怀疑宏只是放弃并且不保存它,而不是显示该错误消息。
You can't save files with macros in it to .xlsx format. If you save a file yourself you should get an error message. I suspect the macro just gives up and doesn't save it, rather than displaying that error message.