public ActionResult ExportExcel(string Id)
{
//建立Excel
ExcelPackage ep = new ExcelPackage();
//填入資料
//建立第一個Sheet,後方為定義Sheet的名稱
ExcelWorksheet sheet1 = ep.Workbook.Worksheets.Add("頁簽1");
int col = 1; //欄:直的,因為要從第1欄開始,所以初始為1
//第1列是標題列
sheet1.Cells[1, col++].Value = "標題1";
sheet1.Cells[1, col++].Value = "標題2";
sheet1.Cells[1, col++].Value = "標題3";
sheet1.Cells[1, col++].Value = "標題4";
//資料從第2列開始
int row = 2; //列:橫的
int rowcount = 1;
col = 1;//每換一列,欄位要從1開始
//指定Sheet的欄與列將資料寫入
sheet1.Cells[row, col++].Value = rowcount;
sheet1.Cells[row, col++].Value = "";
sheet1.Cells[row, col++].Value = "";
sheet1.Cells[row, col++].Value = DateTime.Now.ToString("yyyy-MM-dd");
row++;
rowcount++;
//Excel檔名
var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
//Save the file to server temp folder
string fullPath = Path.Combine(Server.MapPath("~/FileTemp"), fileName);
MemoryStream fileStream = new MemoryStream();
ep.SaveAs(fileStream);
ep.Dispose();要記得先將資料寫進MemoryStream在Dispose。
fileStream.Position = 0;//不重新將位置設為0,excel開啟後會出現錯誤
return File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
建置一下來看看前端的畫面,按下匯出Excel,結果GG
原來是要再加入設定
在Web.config中的appSettings中加入設定
<add key="EPPlus:ExcelPackage.LicenseContext" value="NonCommercial" />
再來一次
打開Excel