简体   繁体   English

从asp.net C#中的数据集中导出Excel文件

[英]export excel file from dataset in asp.net C#

我在sql server中有数据,我想使用asp.net C#导出到数据

This example shows how to extract data from SQL Server into Excel spreadsheet using a single dataset, and two distinct DataAdapters. 本示例说明如何使用单个数据集和两个不同的DataAdapter将数据从SQL Server提取到Excel电子表格中。

  // fill data from SQL
  var ConnSql= new System.Data.OleDb.OleDbConnection(ConnStringSql);

  var da1 = new System.Data.OleDb.OleDbDataAdapter();
  da1.SelectCommand=  new System.Data.OleDb.OleDbCommand(sqlSelect);
  da1.SelectCommand.Connection= ConnSql;

  var ds1 = new System.Data.DataSet();
  da1.Fill(ds1, "Extracto");

  // need to update the rows so the DA does the insert...
  foreach (System.Data.DataRow r in ds1.Tables[0].Rows) { 
    r["Extracted"]= System.DateTime.Now; // update one column in each row
  }

  // insert into Excel
  var ConnExcel= new System.Data.OleDb.OleDbConnection(ConnStringExcel);
  var da2 = new System.Data.OleDb.OleDbDataAdapter();

  da2.UpdateCommand= new System.Data.OleDb.OleDbCommand(sqlInsert);
  da2.UpdateCommand.Connection= ConnExcel;

  da2.UpdateCommand.Parameters.Add("@ProductId", System.Data.OleDb.OleDbType.Integer, 4, "ProductId");
    ..etc..

  da2.Update(ds1, "Extracto");

You can also export it in a CSV file separated by comma "," or other separators. 您也可以将其导出为以逗号“,”或其他分隔符分隔的CSV文件。 For this you have to use StreamWriter object for writing text file and looping through the dataset. 为此,您必须使用StreamWriter对象编写文本文件并遍历数据集。

Spreadsheetgear is a really great tool for this type of thing - very fast and easy to use. Spreadsheetgear是用于此类事物的非常有用的工具-非常快速且易于使用。 I only wish they had a less expensive version, at just under $1000 its pricey, but seems to do all that it is advertised to. 我只希望他们有一个更便宜的版本,其价格不到1000美元,但似乎可以做广告所宣传的一切。

Lets you not only export the data, but formats, colors, fonts and graphs too. 使您不仅可以导出数据,还可以导出格式,颜色,字体和图形。

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

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