创建2007/2010 Excel文件并保存到服务器
本文关键字:保存 服务器 文件 Excel 2007 2010 创建 | 更新日期: 2023-09-27 18:06:07
我正在使用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());