在mvc 4中仅保存一页Excel时,获取NULL对象异常

时间:2015-04-08 06:46:53

标签: c# excel openxml-sdk

以下是我的代码..我有Excel模板,包含2或3张表。当我在所有excel上执行并保存数据时它会成功但是如果我只处理一个excel表,它会在xlPackage.Save()上抛出异常; 如何只保存一张Excel

String filePath = string.Format(ConfigurationManager.AppSettings["IcxFileFormatPath"]);
filePath += @"\ARK_New_FromDeviceSettings.xlsx";
String Template = string.Format(ConfigurationManager.AppSettings["IcxFileFormatTempPath"]);
FileInfo newFile = new FileInfo(filePath);
FileInfo UITemplate = new FileInfo(Template + @"\ARK_New_FromDeviceSettings.xlsx");

using (ExcelPackage xlPackage = new ExcelPackage(newFile, UITemplate))
{             
    ExcelWorksheet systemWorksheet = xlPackage.Workbook.Worksheets["System Details"];

    if (systemWorksheet != null)
    {
        const int startRow = 2;
        int row = startRow;
        // DataTable dt
        foreach (var systemDetailList in systemDetail)
        {
            if (row > startRow)
                systemWorksheet.InsertRow(row);
            systemWorksheet.Cell(row, 1).Value = Convert.ToString(systemDetailList.ModbusTCPIDofDCUDevice);
            systemWorksheet.Cell(row, 2).Value = systemDetailList.DCUSerialNumber;
        }
   }
   xlPackage.Save();
}

// HttpContext context = HttpContext.Current;
Response.Clear();
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=UIRateTemplate.xlsx");
Response.WriteFile(filePath);
Response.Flush();
Response.End();

1 个答案:

答案 0 :(得分:0)

如果没有“系统详细信息”工作表,除了保存ExcelPackage之外不执行任何操作,为什么不在该紧密括号之前将行“xlPackage.Save()”移动一行?它将不再保存,但您无论如何都不会进行任何更改,并且您将消除NullReferenceException。