Export data as Excel file from ASP.NET

后端 未结 5 1086
半阙折子戏
半阙折子戏 2020-12-17 05:27

I have data like below

AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE

Now there is a button on the page, and when I click the button, the browser would

5条回答
  •  悲&欢浪女
    2020-12-17 05:57

    Short of automating excel on your server, which is not recommended, the easiest way is to use a string builder to create the required output and then write this to the HttpResponse setting the content type to "text/csv", setting the appropriate header information.

    While this is not strictly an excel document the user downloading the file will be prompted to open it in excel if they have it installed or alternatively any other spreadsheet based editor.

    The following snippet should get you going:

    string docName  = "MyExcelDoc"
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("AAAAAA");
    sb.AppendLine("BBBBBB");
    
    context.Response.ClearContent();
    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("content-disposition", "attachment; filename=" + docName + ".csv");
    context.Response.Write(sb.ToString());            
    context.Response.Flush();
    

提交回复
热议问题