Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - Export data as Excel file from ASP.NET

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 download an Excel file with the data above, and stay on the current page. Is there any simple way to do it? The data is very simple. Only one column, and not huge.

Best Regards,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  • HTML
  • CSV
  • Spreadsheet XML
  • OOXML (.xlsx)

If you want to use OOXML there are libraries such as Simple OOXML. Note this is the .xlsx format.

The following code sets the headers required for a .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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...