I would like to export data from a SQL Server pull (usually I use SqlDataReader
, but am open to suggestions) into an Excel/CSV file and have the user of the web app get it as a download.
I'd like to do this AJAX style, so that the click on download won't cause a reload/postback.
Anyone done this before or have an idea on how?
I think this mechanism would work.
Have an HTML button that calls a javascript function when clicked.
<input id="downloadbtn" type="button" value="Download" onclick="download();" />
Function would look something like this:
var download = function() {
$.ajax({
url: "datamaker.aspx",
context: document.body
}).done(function(data) {
// parse response data, get file path
var filepath = ParseDataToGetFilePath(data);
// open the csv file path in a new window (which will begin download)
window.open(filepath, '_blank');
});
};
In the serverside, "datamaker.aspx" should connect to the SQL Server, and create the CSV file. Creating a CSV file is as easy as creating any other file using streamwriter, and writiing "comma" between fields. At the end of this page, output the filename either in a response xml or json.
{ filepath: \path\datafile.csv }
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.