我正在编写一个模块,使用 Microsoft.Office.Interop.Excel
将 DataTable 导出到 Excel,但在认真开始之前,我想了解最基本的工作:打开文件,另存为并关闭。
我已成功打开和保存扩展名为 .xls 的文件,但无法使用扩展名为 .xlsx 的文件进行保存。它写入 .xlsx 文件,但当我尝试打开它时出现以下错误:
Excel cannot open the file 'SomeFile.xlsx' because the file format is not valid. Verify that file has not been corrupted and that the file extension matched the format of the file.
我用来打开、保存和关闭文件的代码是:
Excel.Application excelApplication = new Excel.Application();
//excelApplication.Visible = true;
//dynamic excelWorkBook = excelApplication.Workbooks.Add();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
//Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
int rowIndex = 1; int colIndex = 1;
excelApplication.Cells[rowIndex, colIndex] = "TextField";
// This works.
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xls", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// This does not!?
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xlsx", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
我也尝试过文件格式 Excel.XlFileFormat.xlExcel12
代替 Excel.XlFileFormat.xlWorkbookNormal
但这甚至没有写入而是抛出 COMException:
Exception from HRESULT: 0x800A03EC
如能提供解决此问题的任何帮助,我们将不胜感激。
编辑:我现在也尝试过:
excelWorkBook.SaveAs("C:\\MyExcelTestTest", Excel.XlFileFormat.xlExcel12,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
最佳答案
这就是将相关文件保存为 Excel12 (.xlsx) 文件的方式...这并不是您直觉上认为的那样,即使用 Excel.XlFileFormat.xlExcel12
而是 Excel。 XlFileFormat.xlOpenXMLWorkbook
。实际的 C# 命令是
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
我希望这对以后的其他人有帮助。
Missing.Value
在 System.Reflection
命名空间中找到。
关于c# - 使用 Microsoft.Office.Interop.Excel 另存为错误导出到 .xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9769703/