2014-06-16 94 views
0

我使用按鈕單擊和函數從SQL Server 檢索的數據動態創建Excel工作表。目前一切正常,因爲我有300多條記錄,但我擔心更多記錄的表現。從SQL服務器表數據創建Excel工作表

如果我有一萬條記錄,我需要對代碼進行哪些修改,以便在動態創建頁面時不會遇到任何錯誤?

下面是我使用的代碼:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    using (SqlConnection con = new SqlConnection(connectionString)) 
    { 

     SqlCommand cmd = new SqlCommand("usp_myReport", con); 
     cmd.CommandType = CommandType.StoredProcedure; 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     Excel_FromDataTable(dt); 
     Label1.Text = "Excel file created"; 
    } 
} 

下面的功能是:

private static void Excel_FromDataTable(DataTable dt) 
{ 

    Excel.Application excel = new Excel.Application(); 
    Excel.Workbook workbook = excel.Application.Workbooks.Add(true); 

    int iCol = 0; 
    string[] colNames = new string[dt.Columns.Count]; 
    foreach (DataColumn c in dt.Columns) 
    { 
     colNames[iCol++] = c.ColumnName; 
     char lastColumn = (char)(65 + dt.Columns.Count - 1); 
     excel.get_Range("A1", lastColumn + "1").Value2 = colNames; 
     } 

    int iRow = 0; 
    foreach (DataRow r in dt.Rows) 
    { 
     iRow++; 
        iCol = 0; 
     foreach (DataColumn c in dt.Columns) 
     { 
      iCol++; 
      excel.Cells[iRow + 1, iCol] = r[c.ColumnName]; 
     } 
    } 

    object missing = System.Reflection.Missing.Value; 

    workbook.SaveAs("MyExcelWorkBook.xls", 
     Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing, 
     false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
     missing, missing, missing, missing, missing); 
    excel.Visible = true; 
    Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet; 
    ((Excel._Worksheet)worksheet).Activate(); 
    ((Excel._Application)excel).Quit(); 

} 
+0

@Dhavel - 目前我不h大量的記錄......但正如前面說的預見未來使用..要使代碼穩定...沒有pagetimeout ..代碼執行需要很長時間... – Itniv

+2

作爲一般觀點,你可能想看看[ EPPlus](http://epplus.codeplex.com/)包,而不是自己做Excel的COM自動化。 – PhilPursglove

+0

@ Itniv你試過使用*** EPPlus ***嗎? – Kiquenet

回答

0

嘗試這個

讓您在數據表中的數據,然後使用此功能

public void ExportToExcel_AsXlsFile(DataTable dt, string file_name) 
     { 
      var grid = new GridView(); 
      grid.DataSource = dt; 
      grid.DataBind(); 
      Response.ClearContent(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment; filename='" + file_name + "'.xls"); 
      Response.ContentType = "application/ms-excel"; 
      Response.Charset = ""; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      grid.RenderControl(htw); 
      Response.Output.Write(sw.ToString()); 
      Response.Flush(); 
      Response.End(); 
     }