[英]C# Error while opening programmatically generated Excel file from a C# desktop application: "File format or file extension is not valid"
我正在使用以下代碼從使用 Microsoft.Office.Interop.Excel 的 C# WinForms 應用程序生成 Excel .xlsx 文件
到目前為止,代碼只是創建了一個空白的 Excel 文件。 當我嘗試打開 xlsx 文件時,出現以下錯誤。 但是,如果我將文件擴展名重命名為 .xls,該文件將打開文件。
void WriteData(DataSet ds, string excelFilePath)
{
Excel.ApplicationClass appExcel = null;
Excel.Workbooks workbooks = null;
Excel.Sheets workSheets = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Workbook wbTemplate = null;
Excel.Range range = null;
try
{
appExcel = new Excel.ApplicationClass();
ExcelUtils.InitExcel(appExcel);
workbooks = appExcel.Workbooks;
wb = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
wb.SaveAs(excelFilePath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
wb.Close(Type.Missing, Type.Missing, Type.Missing);
}
finally
{
ExcelUtils.CleanupExcel(appExcel, workbooks, workSheets, wb, ws);
appExcel = null;
}
}
我讀過其他類似的問題,但其中大部分是其他語言或使用某些 Excel 庫。 我需要使用 Excel Interop 的解決方案。 我不想以 OpenXML 格式保存。
您在保存文件時使用了錯誤的XlFileFormat
成員作為您想要的格式。
根據文檔:
xlWorkbookNormal
用於*.xls
文件。xlWorkbookDefault
用於*.xlsx
文件。 改為傳遞Excel.XlFileFormat.xlWorkbookDefault
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.