匯出Excel算是很常用到的功能,所以記下來
1.建立一個Web 專案
2.使用Nuget Key 下EPPlus 並安裝
<div class="row">
<div class="col-4">
</div>
<div class="col-6">
<h6>
<a href="@Url.Action("ExportExcel","Home",new { Id = 1 }) " class="btn btn-success">
匯出Excel
</a>
</h6>
</div>
</div>
假設需要帶參數如Id 就如圖,否則只需要@Url.Action("ExportExcel","Home")
4.再來是HomeController的部份先把需要的using 進來
using OfficeOpenXml;
using System.IO;
5.接下來是程式碼的部份
建立一個 public ActionResult ExportExcel(string Id)
Id是用來接收前端剛剛設定的參數
接下來直接上碼
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
原來是要再加入設定
<add key="EPPlus:ExcelPackage.LicenseContext" value="NonCommercial" />
再來一次
打開Excel






沒有留言:
張貼留言