简体   繁体   中英

Exporting data to Excel

I need to export data to a formatted Excel document.

Basically, a non-technical person should be able to create (or just modify) an Excel document that will be the template for the export process.

The template should describe headers, used fields, etc. Knowing the template I have to export data to this document. Basically, it will look something like this:

Header
{record.Name}

The template document will be quite complicated - it will have custom formatting, tabs, etc. However, formatting cells is not my task, I just need to fill the document with data. I will need to export not only single fields but also lists so I will need to add rows to the document for every element in the list.

Currently, I'm using Excel 2003, but I can change it to Excel 2007 if this version supports better integration.

I don't know if Excel allows this kind of integration out of the box, but for me it is not important if I had to define some custom tags in the Excel document or use some third party library.

I'm using .NET 3.5 and C#.

You can export controls to in a page to Excel with the MIME as Excel:

private void Button1_Click(object sender, System.EventArgs e)
{
    //Export to excel.
    Response.Clear();
    Response.Buffer= true;
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";
    this.EnableViewState = false;
    System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
    this.ClearControls(datagrid);
    datagrid.RenderControl(oHtmlTextWriter);
    Response.Write(oStringWriter.ToString());
    Response.End();
}

See the "Export ASP.NET DataGrid to Excel" tutorial for further details.

There are at least 2 ways of integrating with Excel

  1. OLE Automation - there are components in VS that enable you to open, close and manipulate excel. This works with all versions including 2003.
  2. Linq to Excel. This works only with the new version(or if you have plugin installed for the new file format).

Personally I think that second option is better here, because you will certainly need linq capabilities to do that kind of work.

I ended up using xml datasource in excel and creating xml mappings. Thanks to this, I get nice template that non-tech users may edit, and in code I create only xml description of my data. Before you can use it, you have to create xsd file that define schema of your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM