System.runtime.InteropServices.Comexception Microsoft Interop C#

时间:2018-04-03 18:42:01

标签: c# excel

我在C#中写入Excel工作表时收到此错误。写完4,500行后会弹出一个错误:

  

System.Runtime.InteropServices.COMException(0x800AC472):来自HRESULT的异常:0x800AC472
    在System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult,ExcepInfo& excepInfo,UInt32 argErr,String message)
    在CallSite.Target(Closure,CallSite,ComObject,String)
    在CallSite.Target(Closure,CallSite,Object,String)
    在PaymentVarReadPDFMurfreesboro.ConvertPdfToExcel.writeToExcel(String filePath)

以下是打开并写入excel的代码。

public void writeToExcel(string filePath)
{
    try
    {
        ExcelUse.Application excel = new ExcelUse.Application();
        excel.Visible = true;
        excel.DisplayAlerts = false;
        ExcelUse.Workbook wb = excel.Workbooks.Open(filePath);
        ExcelUse.Worksheet sh2 = wb.Worksheets.get_Item("Sheet1");

        for (int i = 2; i <= finalList.Count+1; i++)
        {
            sh2.Cells[i, "A"].Value2 = finalList[i-2].ToString().Substring(33, 8);
            sh2.Cells[i, "B"].Value2 = finalList[i-2].ToString().Substring(44, 7);
            sh2.Cells[i, "C"].Value2 = finalList[i-2].ToString().Substring(117, 7);
        }

        wb.Save();
        wb.Close(true);
        excel.Quit();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

我之前使用过此代码来写入Excel工作表。但由于某种原因,它无法正常工作。我认为它与它写的行数有关。

0 个答案:

没有答案