将DataReader行写入Excel文件

时间:2012-02-02 21:31:51

标签: asp.net ado.net asp.net-1.1

我在SQL Server 2000中有数据并且有一个HyperLink,它转到一个传递形式,其代码隐藏将数据输出到Excel文件。我一直在关注这个教程:

http://www.dzone.com/links/r/export_gridview_to_excelcsv_in_net_using_c.html

我成功地从DataReader输出了一些样本值。我遇到的第一个问题是1.1中没有DataTable Load方法。我有数据通过DataReader返回,但我需要帮助的是如何创建标题并将它们与数据行一起输出到Excel文件......

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;

string attachment 
    = "attachment;filename=Report_" + DateTime.Now.ToString() + ".xls"; 
Response.AddHeader("content-disposition", attachment);

Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.ContentType = "application/ms-excel";

DataTable dt = new DataTable();
dt.Columns.Add("Company");
dt.Columns.Add("Address1");
dt.Columns.Add("Address2");
dt.Columns.Add("City");
dt.Columns.Add("State");
dt.Columns.Add("ZipCode");

SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();
con.ConnectionString = "myconnstring";
com.Connection = con;
com.CommandText 
    = "SELECT DISTINCT  Company, Address1, Address2, City, State, ZipCode" + 
      " FROM Vendor_View";
con.Open();

SqlDataReader dr = com.ExecuteReader();
while(dr.Read())
{
    // how to grab and output data to Excel? 
}

2 个答案:

答案 0 :(得分:4)

我自己写了一篇关于此的博客post。基本上有3种选择。但我推荐这个:

//Make sure you add this reference and have it imported
Using Excel = Microsoft.Office.Interop.Excel;

protected void xlsWorkBook()
{
     Excel.Application oXL;
     Excel.Workbook oWB;
     Excel.Worksheet oSheet;
     Excel.Range oRange;
     // Start Excel and get Application object.
     oXL = new Excel.Application();
     // Set some properties
     oXL.Visible = true;
     oXL.DisplayAlerts = false;
     // Get a new workbook.
     oWB = oXL.Workbooks.Add(Missing.Value);
     // Get the active sheet
     oSheet = (Excel.Worksheet)oWB.ActiveSheet;
     oSheet.Name = “Customers”;
     // Process the DataTable
     // BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
     //DataTable dt = Customers.RetrieveAsDataTable();//commented
     DataTable dt = Table;//added
     Session["dt"] = dt;//added
     int rowCount = 1;
     foreach (DataRow dr in dt.Rows)
     {
        rowCount += 1;
        for (int i = 1; i < dt.Columns.Count + 1; i++)
        {
            // Add the header the first time through
            if (rowCount == 2)
            {
               oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
            }
       oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
        }
    }
    // Resize the columns
    oRange = oSheet.get_Range(oSheet.Cells[1, 1],
    oSheet.Cells[rowCount, dt.Columns.Count]);
    oRange.EntireColumn.AutoFit();
    // Save the sheet and close
    oSheet = null;
    oRange = null;
    oWB.SaveAs(“test.xls”, Excel.XlFileFormat.xlWorkbookNormal,
    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
    Excel.XlSaveAsAccessMode.xlExclusive,
    Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value);
    oWB.Close(Missing.Value, Missing.Value, Missing.Value);
    oWB = null;
    oXL.Quit();
    // Clean up
    // NOTE: When in release mode, this does the trick
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
}

答案 1 :(得分:3)

如果是简单数据,则只发出一个CSV文件。 Excel可以配置为非常容易地打开它们。

以下内容可以帮助您入门:

response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment;filename=report.csv;");
response.AddHeader("Pragma", "no-cache");
response.AddHeader("Expires", "0");

// 1. output columns
Boolean addComma = false;
response.Write("\"");
foreach (DataColumn column in _dataToProcess.Columns) {
    if (addComma) {
        response.Write("\",\"");
    } else {
        addComma = true;
    }
    response.Write(column.ColumnName.ToString());
} // foreach column
response.Write("\"");


response.Write(System.Environment.NewLine);

// 2. output data
foreach (DataRow row in _dataToProcess.Rows) {
    addComma = false;
    response.Write("\"");
    foreach (Object value in row.ItemArray) {
        // handle any embedded quotes.
        String outValue = Convert.ToString(value).Replace("\"", String.Empty);
        if (addComma) {
            response.Write("\",\"");
        } else {
            addComma = true;
        }
        response.Write(outValue);
    }
    response.Write("\"");
    response.Write(System.Environment.NewLine);
} // foreach row