Writing DataReader Rows to Excel File

本秂侑毒 提交于 2019-12-01 11:21:30

问题


I've got data in SQL Server 2000 and have a HyperLink that goes to a pass-through form whose code-behind will output the data to an Excel file. I've been following this tutorial:

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

I have succeeded in outputting some sample values from the DataReader. First problem I'm encountering is that there is no DataTable Load method in 1.1. I have data coming back via the DataReader but what I need help with is how to create the headers and output them, along with the rows of data, to the Excel file...

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? 
}

回答1:


If it's simple data, then just emit a CSV file. Excel can be configured to open those pretty easily.

Something like the following would get you started:

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



回答2:


I myself wrote a blog post about this. Basically there are 3 alternatives. But I recommend this one:

//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();
}


来源:https://stackoverflow.com/questions/9120320/writing-datareader-rows-to-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!