我使用了导出到Excel功能,如下所示:
var table = getReport(param1, param2, param3);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.ContentType = "application/vnd.ms-excel";
System.Web.UI.WebControls.GridView grd = new System.Web.UI.WebControls.GridView();
grd.DataSource = table; // give datasource here
grd.DataBind();
StringWriter swr = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(swr);
grd.RenderControl(tw);
Response.Write(swr.ToString());
Response.End();
return View();
其中getReport以表格格式返回数据。 现在这将创建一个新的excel文件,但我想使用现有的Excel模板来创建excel输出。 如何将这样的模板添加到项目以及如何将数据与它绑定?
答案 0 :(得分:0)
您现在使用的方法是将HTML字符串写入Response并在Response标头中将ContentType设置为Excel。这不会创建真正的Excel文件,它只是强制浏览器在Excel中启动文件,并且Excel能够处理HTML文件。使用此方法无法添加模板。
如果要将现有Excel文件用作模板,则需要使用可以创建和修改真实Excel文件的API,例如OfficeWriter。以下是如何使用OfficeWriter将DataTable直接绑定到模板文件的示例。
using SoftArtisans.OfficeWriter.ExcelWriter;
ExcelTemplate xlt = new ExcelTemplate();
//Open the template file
xlt.Open(pathToTemplateFile);
//Create a DataBindingProperties object
DataBindingProperties props = xlt.CreateDataBindingProperties();
// Call the BindData method, passing the DataTable and a name for the datasource
// which will be referenced in the "data markers" in the template
xlt.BindData(table, "DataSource1", props);
//Call the Process method, which binds the data and generates the output file
xlt.Process();
//Stream the file to the Response
xlt.Save(Response, "Report.xls", false);
免责声明:我为OfficeWriter的制作人SoftArtisans工作