【问题标题】:export to excel using existing excel template使用现有的 excel 模板导出到 excel
【发布时间】:2014-02-12 01:15:37
【问题描述】:

我使用了以下导出到 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 输出。 如何将这样的模板添加到项目中以及如何与它绑定数据?

【问题讨论】:

    标签: export-to-excel


    【解决方案1】:

    您现在使用的方法是将 HTML 字符串写入响应并在响应标头中将 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 工作

    【讨论】:

      猜你喜欢
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多