以c编程编写后Excel文件损坏#
问题描述:
我正在开发基于c#的应用程序来处理excel文件。每当我写入excel文件时,文件会被损坏,并且在打开时没有任何内容出现。另外,下一次当应用程序显示异常时,我无法打开该文件。 代码变为如下:以c编程编写后Excel文件损坏#
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public void WriteResultsToSheet()
{
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(filePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
mWSheet1 = (Excel.Worksheet)mWorkBook.Sheets[sheetName.TrimEnd('$')];
Excel.Range range = mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
for (int index = 1; index <= rowCount; index++)
{
try
{
Console.WriteLine(dataGridViewScript.Rows[index].Cells[4].Value.ToString());
}
catch (NullReferenceException nre)
{
if (nre.Message == "Object reference not set to an instance of an object.")
break;
}
Console.WriteLine(dataGridViewScript.Rows[index].Cells[5].Value.ToString());
}
mWorkBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
mWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
oXL.Quit();
mWSheet1 = null;
mWorkBook = null;
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MessageBox.Show("Results exported successfully.");
}
例外情况是如下: 收到COMException了未处理。 由于文件格式或文件扩展名无效,Excel无法打开该文件。验证文件没有损坏。
答
由于文件扩展名,该文件与Excel不兼容。尝试将文件扩展名更改为.xls,如果它是.xlsx,反之亦然,然后尝试再次打开它。
嗨!将数据写入Excel工作表的代码在哪里? –
即使这段代码导致Excel损坏。我怀疑保存或以错误的方式关闭会导致这种情况。请帮忙。 – akashagrawal