我有一个数据表,其中包含多列和日期,数据类型为 "DATE"。
我尝试了以下选项:
1)第三方DLL- ExcelLibrary 如果数据集中没有日期列,则它可以正常工作,否则它会使用一些虚拟值(如-65284)代替日期。
ExcelLibrary.DataSetHelper.CreateWorkbook(@"C:\Users\ABC\Documents\Excel\Report123.xls", ds);
2) 使用简单导出格式而不使用第三方DLL,如下所示
public void ExportToExcel(System.Data.DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "Report123.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
以上代码可以完美地提取Excel,但当我们打开同一个Excel时,会出现格式错误的错误。
我也想读取同一个文件到datatable中,以存储到数据库中。当我尝试读取创建的Excel文件(通过第二个选项)时,我会得到外部表格不符合预期格式的错误。如果我将同一文件另存为,则可以正常工作。
但我不想每次都“另存为”文件,请帮我解决这个问题。
更新:
public void ExportToExcel1(System.Data.DataTable dt)
{
//clear the response of any junk. This may not be necessary
Response.Clear();
//add a header so it has a nice file name
Response.AddHeader("content-disposition", "attachment;filename=Reportengg.xlsx");
//Set the MIME type correctly
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//create a new package, this is the equivalent of an XLSX file.
var package = new ExcelPackage();
//Add a new sheet to the workbook
var sheet = package.Workbook.Worksheets.Add("Sheet1");
//EPPlus contains helper function to load data from a DataTable, though you could manually fill in rows/column values yourself if you want
sheet.Cells["A1"].LoadFromDataTable(dt, true);
// byte[] array = package.GetAsByteArray();
//write the file bytes to the response
Response.BinaryWrite(package.GetAsByteArray());
//end the response so we don't send anymore down and corrupt the file
Response.End();
}