我正在将表数据导出到excel,但出现以下详细信息错误: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'OfficeOpenXml.ExcelColumn'.'
. 我用的是excelpackage。
我的代码方法是:
public void ExportToExcel()
{
//FECTH DATA FROM DB
List<ExcellExport> excellExports = db2.MaintenanceWorkFlows.Select(
x => new ExcellExport
{
MaintenanceId = x.MaintenanceId,
RequisitionNo = x.RequisitionNo,
MaintenanceDate = x.MaintenanceDate,
MaintenanceFrequency = x.MaintenanceFrequency,
ContractNo = x.ContractNumber,
ContractorName = x.ContractorName,
MaintenanceStatus = x.MaintenanceStatus
}).ToList();
从这里开始。我使用excel包导出数据
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("ExpiredContracts");
ws.Cells["A1"].Value = "Report";
ws.Cells["B1"].Value = "Expired Contracts Report";
ws.Cells["A1"].Value = "Date";
ws.Cells["B1"].Value = string.Format("{0:dd MMMM yyy} at {0:H:mm tt}", DateTimeOffset.Now);
ws.Cells["A4"].Value = "MainenanceId";
ws.Cells["B4"].Value = "RequisitionNo";
ws.Cells["C4"].Value = "MaintenanceDate";
ws.Cells["D4"].Value = "MaintenanceFrequency";
ws.Cells["E"].Value = "ContractNo";
ws.Cells["F4"].Value = "ContractorName";
ws.Cells["G4"].Value = "MaintenanceStatus";
int rowStart = 10;
foreach(var item in excellExports)
{
ws.Cells[string.Format("A{0}", rowStart)].Value = item.MaintenanceId;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.RequisitionNo;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.MaintenanceDate;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.MaintenanceFrequency;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.ContractNo;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.ContractorName;
ws.Cells[string.Format("A{0}", rowStart)].Value = item.MaintenanceStatus;
}
ws.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.Openxmlformats.Officedocument-spreadsheetml.sheet";
Response.AddHeader("content-disposition" ,"attachment:filename="+"ExpiredContractsReport.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
我做错什么了?我看过代码,但没有解决问题。
暂无答案!
目前还没有任何答案,快来回答吧!