简体   繁体   English

在Web应用程序中将SQL Server数据导出到Excel

[英]Export SQL Server data to Excel in a web app

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. 我想将数据从SQL Server拉(通常我使用SqlDataReader ,但愿意接受建议)导出到Excel / CSV文件中,并让Web应用程序的用户将其下载。

I'd like to do this AJAX style, so that the click on download won't cause a reload/postback. 我想做这种AJAX样式,以便单击下载不会引起重新加载/回发。

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. 单击时有一个HTML按钮可调用javascript函数。

<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. 在服务器端,“ datamaker.aspx”应连接到SQL Server,并创建CSV文件。 Creating a CSV file is as easy as creating any other file using streamwriter, and writiing "comma" between fields. 创建CSV文件与使用streamwriter创建任何其他文件以及在字段之间写“逗号”一样容易。 At the end of this page, output the filename either in a response xml or json. 在此页面的末尾,以响应xml或json输出文件名。

     { filepath: \path\datafile.csv }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM