【发布时间】:2017-01-17 21:44:18
【问题描述】:
我打开一个现有的 .xlsx 文件,对其进行更改,然后将其保存回磁盘。更改正在起作用,但是当我尝试打开文件(手动,通过在 Windows 资源管理器中单击 2 次)时,我得到,“Excel 无法打开文件 'Bla.xlsx',因为文件格式或文件扩展名无效。请确认文件没有损坏,并且文件扩展名与文件格式匹配。"
如果我将扩展名从“xlsx”更改为“xls”,它会正常打开。但原始文件是 .xlsx,我想保持这种状态。这是我的代码:
// Open the file
MSExcel.Excel.ApplicationClass xlApp = new MSExcel.Excel.ApplicationClass();
MSExcel.Excel.Workbook xlBook = xlApp.Workbooks.Open(sourceFilename, 0, false, 5, null, null, false, MSExcel.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
MSExcel.Excel.Sheets xlSheets = xlBook.Worksheets;
MSExcel.Excel.Worksheet xlSheet = (MSExcel.Excel.Worksheet)xlSheets.Item[1];
// Change the file
MSExcel.Excel.Range priceTypeCell = (MSExcel.Excel.Range)xlSheet.Cells[7, 3];
//if (priceTypeCell.Value2.ToString() == "Price Push") <= This is probably fine, but just in case...
if (priceTypeCell.Value2.ToString().Trim().Contains("Price Push"))
{
priceTypeCell.Value2 = "Price Type";
}
// Save the file - example code showed xlWorkbookDefault, but that either never existed or
// has been deprecated; xlWorkbookNormal is what I chose from the limited available options
xlApp.DisplayAlerts = false; // Was prompting about overwriting the existing file
xlBook.SaveAs(sourceFilename, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlBook.Close();
我使用的代码有什么问题?我从here(Igby Largeman 的回答)改编了它,但不得不更改 xlWorkbookDefault,因为它未被识别。我尝试了 xlWorkbookNormal 和 xlExcel7,但都保存为 .xlsx 但只有更改为 .xls 才会打开。
奇怪的是,也许xlWorkbookDefault 确实在官方列表here(最后一个条目)中。
更新
当我将类型更改为“Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet”(最接近我找到的“xlOpenXMLWorkbook”)时,我得到这样保存的文件稍后以编程方式重新打开时出现异常:
System.Runtime.InteropServices.COMException was unhandled
HelpLink=C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM
HResult=-2146827284
Message=Excel cannot open the file 'ARAMARK-04-03-2016 DISTRIBUTOR COPY.xlsx' because the file format or file extension is not
valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
更新 2
当我尝试使用“xlExcel9795”时,它甚至不会保存它。我得到了:
System.Runtime.InteropServices.COMException was unhandled
HResult=-2146827284
Message=Exception from HRESULT: 0x800A03EC
Source=Microsoft.Office.Interop.Excel
ErrorCode=-2146827284
StackTrace:
at Microsoft.Office.Interop.Excel.WorkbookClass.SaveAs(Object Filename, Object FileFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, Object AddToMru, Object TextCodepage, Object TextVisualLayout, Object Local)
at PricePushETLProcess.PricePushFile.ChangeColumnHeaderVal(PricePushFile ppf) in . . .
【问题讨论】:
标签: c# excel xls xlsx excel-interop