【问题标题】:Writing DataReader Rows to Excel File将 DataReader 行写入 Excel 文件
【发布时间】:2012-02-25 13:54:00
【问题描述】:

我在 SQL Server 2000 中有数据,并且有一个超链接,它转到一个传递表单,其代码隐藏会将数据输出到 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? 
}

【问题讨论】:

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


    【解决方案1】:

    如果是简单数据,则只需发出 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
    

    【讨论】:

    • 那么标题(列名)呢?
    • 感谢 Chris,从您的代码示例中获得了解决方案以及以下内容:itjungles.com/dotnet/…
    【解决方案2】:

    我自己为此写了一篇博客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();
    }
    

    【讨论】:

    • 谢谢,我明天试试,然后回来:)
    • 好的,兄弟,晚安。所有 3 种方法都有效。只需选择 1。:)
    • 不想使用互操作。是否可以以示例 1 为例,将 Gridview 排除在外 - 只需将数据从 DB 直接获取到 Excel?
    • @rofans91 非常感谢您拯救了我的一天。是否可以将excel文件的标题加粗以便更好看?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2019-04-12
    相关资源
    最近更新 更多