简体   繁体   中英

Exporting Repeater Data to Excel in C# .net

I have to Provide the functionality to export all the data shown in repeater to excel file. I have successfully done that but the file size goes above 4MBs.

Here is the code I am using.

public void ExportToExcel(Repeater name)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    Repeater rp = name;
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

    foreach (RepeaterItem item in name.Items)
    {
        item.Controls.Remove(item.FindControl("hd_Depot"));
        item.Controls.Remove(item.FindControl("hd_ProdCode"));
        item.Controls.Remove(item.FindControl("hd_Closing"));
        item.Controls.Remove(item.FindControl("hd_groupName"));

    }
    rp.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

Now when I use xls or xlsx it downloads perfectly but with large size but if I use csv it writes the whole html code to excel file. my main motive here is to shrink the size of the excel file to less than 1MB. Please advise.

It looks like you write an HTML or CSV file and pretends it is an Excel sheet in the Content-Type so that it opens with Excel. A better solution is to create a real Excel sheet, ie with an xlsx extension, using some library that can do this for you.

I think the xlsx contains the entire html, and that's why it's so big.

If you just want to export to csv:

  • create a string which contains the data (in your for loop)
  • Contenttype is: "text/csv"

I use a kbCSV and the CSVWriter.

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