使用epplus库生成excel [英] Generate excel using epplus library
本文介绍了使用epplus库生成excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用C#中的EPPlus库创建一个excel文件。
但是,我无法打开创建的excel文件,错误信息如下:
找到不可读的内容。
EPPlus库链接: EPPlus - 创建高级Excel电子表格服务器 - 下载:EPPlus 4.1 [ ^ ]
请检查我的代码,让我知道我错过了什么。
我是什么尝试过:
以下提到的是我正在使用的代码:
I am trying to create a excel file using EPPlus library in C#.
However, I'm unable to open the created excel file with error message as following:
"Unreadable content found".
EPPlus library link: EPPlus-Create advanced Excel spreadsheets on the server - Download: EPPlus 4.1[^]
Please check my code and let me know what I am missing.
What I have tried:
Following below mentioned is the code I'm using:
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:E1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.BurlyWood);
rng.Style.Font.Color.SetColor(Color.White);
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "ExcellData.xlsx"));
Response.BinaryWrite(pck.GetAsByteArray());
}
Below mentioned is dummy data for DataTable which I'm currently trying to show in excel:
DataTable dt = new DataTable();
dt.Columns.Add("SkillID");
dt.Columns.Add("SkillName");
dt.Columns.Add("BehaviorID");
dt.Columns.Add("BehaviorName");
dt.Columns.Add("ObjectiveDesc");
DataRow dr1 = dt.NewRow();
dr1[0] = "s11";
dr1[1] = "s1";
dr1[2] = "b11";
dr1[3] = "b1";
dr1[4] = "obj1";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "s11";
dr2[1] = "s1";
dr2[2] = "b22";
dr2[3] = "b2";
dr2[4] = "obj2";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "s11";
dr3[1] = "s1";
dr3[2] = "b33";
dr3[3] = "b3";
dr3[4] = "obj3";
dt.Rows.Add(dr3);
推荐答案
添加Response.End();在写入结束时刷新所有内容。
Add Response.End(); at the end of the write to flush all the contents out.
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
这篇关于使用epplus库生成excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文