我使用EPPlus包从数据表导出Excel 2007文件,但我想保存我在服务器上创建的Excel文件。我正在使用这种方法:
private string SaveExcelFile(DataTable dt)
{
string reportName = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss-fff") + ".xlsx";
Response.Clear();
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"" + reportName + "\"");
using(ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);
wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();
//Response.BinaryWrite(pck.GetAsByteArray());
string filePhysicalPath = Server.MapPath("~/Uploads/PeriodsReports/" + reportName);
System.IO.File.WriteAllBytes(filePhysicalPath, pck.GetAsByteArray());
}
Response.Flush();
Response.End();
return reportName;
}
Excel保存后,我收到此错误:
Excel无法打开文件,因为文件格式或文件扩展名无效
你不能使用WriteAllText
作为二进制文件。(和excel是二进制文件)试试这个
System.IO.File.WriteAllBytes(filePhysicalPath, pck.GetAsByteArray());