Export data as an Excel file from ASP.NET

I have data as below

AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE 

Now there is a button on the page, and when I click the button, the browser loads the Excel file with the data above and remains on the current page. Is there an easy way to do this? The data is very simple. Only one column, not huge.

Best wishes,

+4
source share
5 answers

You can output data directly to the response stream. Set the mime type to succeed and write data as:

  • HTML
  • Csv
  • XML table
  • OOXML (.xlsx)

If you want to use OOXML, there are libraries like Simple OOXML . Please note that this is the .xlsx format.

The following code sets the headers required for the .xls file

 'Send response with content type to display as MS Excel context.Response.Clear() context.Response.Buffer = True context.Response.AddHeader("content-disposition", String.Format( "attachment;filename={0}", fileName)) context.Response.ContentEncoding = Encoding.UTF8 context.Response.Cache.SetCacheability(HttpCacheability.Private) context.Response.ContentType = "application/vnd.ms-excel" 'Write to response context.Response.Write("csv,data,goes,here") context.Response.End() 
+6
source

Yes, you can export the information as a csv file and provide it with an Excel file extension. Excel recognizes a non-native Excel format and allows you to import with a warning. For downloads, you can search the Internet for regular file downloads using the custom MIME type in ASP.NET.

Due to the warning message, the above is not preferred. You can also use the library to create your own Excel file. I have successfully used Aspose.Cells in past projects.

0
source

It was not possible to automate excel on your server, which is not recommended, the easiest way is to use the line builder to create the required output, and then write it to HttpResponse, setting the content type to "text / csv", setting the corresponding header information.

Although this is not strictly an excel document, the user downloading the file will be asked to open it in excel if it is installed or, alternatively, any other spreadsheet editor.

The following snippet should catch you:

 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(); 
0
source

An alternative to the above solutions is to connect to an Excel COM object and create a spreadsheet using their API.

This would mean that you would need to install excel on the server so that other solutions are probably better.

0
source

NPOI is an open source project that can help you read / write xls, doc, ppt files.

It is very simple and provide the correct Excel format.

0
source

Source: https://habr.com/ru/post/1306339/


All Articles