4
Excel告訴我有不可讀的數據,所以在我說要嘗試恢復信息之後,它會顯示正確的數據。但是,當我打開xlsx的文本文件時,我得到了整個頁面的所有html,而不是僅僅是gridview(這可能是Excel討論的不可讀內容)。使用EPPlus,我試圖將一個gridview導出到一個Excel工作表
這裏是我的代碼:
public void ExcelDownload(object sender, EventArgs e)
{
DataSet _MailingListUsers = db.GetMailingList();
DataTable mailTable = _MailingListUsers.Tables[0];
DumpExcel(mailTable);
}
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Mailing List");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A2"].LoadFromDataTable(tbl, false);
//Header Titles
ws.Cells["A1"].Value = "Employee Name";
ws.Cells["B1"].Value = "Email Address";
ws.Cells["C1"].Value = "Phone";
ws.Cells["D1"].Value = "Business Unit";
ws.Cells["E1"].Value = "Site";
ws.Cells["A1"].AutoFitColumns();
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:E1"])
{
rng.Style.Font.Bold = true;
//Set Pattern for the background to Solid
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
//Set color to dark blue
rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=MailingList.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
什麼可能發生的任何想法?在嘗試將HTML數據發送到Excel時遇到同樣的問題後,有人建議使用EPPlus,並且它發送的是整個頁面,而不僅僅是gridView。
感謝
太好了!這工作!謝謝。 – shawleigh17 2012-03-05 21:45:02
最佳解決方案............................................... ........... !!! :D – Butters 2013-11-19 15:40:54
我只想指出第4行應該是這樣的: ws.Cells [「A2」]。LoadFromDataTable(tbl,false); – 2014-03-17 16:08:55