问题描述
我在写一个模块使用数据表导出到Excel的过程的Microsoft.Office.Interop.Excel
,但在认真开始之前,我想要得到的很基础工作:打开文件,另存为,并关闭
我已经成功地打开和保存的.xls扩展名的文件,但与扩展的.xlsx确实节约不行。它写入.xlsx文件,但是当我尝试打开它,我收到以下错误:
The code I use to open, save and close the files is:
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);
I have also tried the file format Excel.XlFileFormat.xlExcel12
in place of Excel.XlFileFormat.xlWorkbookNormal
but this does not even write instead throwing the COMException:
Any help resolving this would be most appreciated.
Edit: I have now also tried:
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);
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12
but Excel.XlFileFormat.xlOpenXMLWorkbook
. The actual C# command was
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);
I hope this helps someone else in the future.
Missing.Value
is found in the System.Reflection
namespace.
这篇关于使用导出另存为的Microsoft.Office.Interop.Excel误差为原来的.xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!