EPPlus
using (ExcelPackage package = new ExcelPackage())
{
//要塞進去的值
var list = db.data5
.Select(a => new
{
date = a.logtime.ToString("yyyy/MM/dd HH:mm"),
a.欄位1,
a.欄位2,
a.欄位3,
a.欄位4,
a.欄位5
}).ToList();
// 新增worksheet
ExcelWorksheet ws = package.Workbook.Worksheets.Add("下面tab的標題");
//創造你要塞進去Eexcl內的Table
DataTable dt = new DataTable();
//創造Table標題
dt.Columns.Add("時間");
dt.Columns.Add("data1");
dt.Columns.Add("data2");
dt.Columns.Add("data3");
dt.Columns.Add("data4");
dt.Columns.Add("data5");
//塞值
for (int i = 0; i <= list.Count()-1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = list[i].date;
dr[1] = list[i].欄位1;
dr[2] = list[i].欄位2;
dr[3] = list[i].欄位3;
dr[4] = list[i].欄位4;
dr[5] = list[i].欄位5;
dt.Rows.Add(dr);
}
// 將DataTable資料塞到sheet中
ws.Cells["A1"].LoadFromDataTable(dt, true);
for(int i=1;i<7;i++)
{
ws.Column(i).AutoFit();
}
// 設定Excel Header 樣式
using (ExcelRange rng = ws.Cells["A1:F1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));
rng.Style.Font.Color.SetColor(Color.White);
}
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "檔案名稱.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}