I am about to add a section to an ASP.NET app (VB.NET codebehind) that will allow a user to get data returned to them as an Excel file, which I will generate based on database data. While there are several ways of doing this, each has its own drawbacks. How would you return the data? I'm looking for something that's as clean and straightforward as possible.
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- How to store image outside of the website's ro
- 'System.Threading.ThreadAbortException' in
- how to use special characters like '<'
- Request.PathInfo issues and XSS attacks
we export data from a datagrid to excel all the time. Converting it to HTML then writing to an excel file
The only gotcha with this method was that a lot of our grids had buttons or links in them so you need this too:
I found that somewhere, it works well.
If you fill a GridView with data you can use this function to get the HTML formatted data, but indicating the browser it's an excel file.
One of the problems I've ran across using one of the solutions suggested above which are similar to this answer is that if you push the content out as an attachment (what I've found to be the cleanest solution for non-ms browsers), then open it in Excel 2000-2003, its type is an "Excel Web Page" and not a native Excel document.
Then you have to explain to users how to use "Save as type" from within Excel to convert it to an Excel document. This is a pain if users need to edit this document and then re-upload it to your site.
My recommendation is to use CSV. It's simple and if users do open it from within Excel, Excel at least prompts them to save it in its native format.
Here's a solution the streams the datatable out as a CSV. Fast, clean, and easy, and it handles commas in the input.
since Excel understands HTML you can just write the data out as an HTML table to a temp file with an .xls extension, get the FileInfo for the file, and blow it back using
if you wanted to avoid the temp file, you could write to an in-memory stream and write the bytes back instead of using WriteFile
if the content-length header is omitted you could just write the html back directly, but this may not work correctly all the time in all browsers
I would just create a CSV file based on the data, because I see that as the cleanest, and Excel has good support for it. But if you require a more flexible format, I'm sure there's some 3rd party tools for generating real excel files.