2012-11-26 31 views
5

我想DataGridView的數據複製到Excel中,我使用這個代碼:簡單的方法導出的DataGridView到Excel

public static void ExportToExcel(DataGridView dgView) 
{ 
    Microsoft.Office.Interop.Excel.Application excelApp = null; 

    try 
    { 
     // instantiating the excel application class 
     object misValue = System.Reflection.Missing.Value; 
     excelApp = new Microsoft.Office.Interop.Excel.Application(); 
     Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing); 
     Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet; 

     currentWorksheet.Columns.ColumnWidth = 18; 

     if (dgView.Rows.Count > 0) 
     { 
      currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s"); 
      int i = 1; 

      foreach (DataGridViewColumn dgviewColumn in dgView.Columns) 
      { 
       // Excel work sheet indexing starts with 1 
       currentWorksheet.Cells[2, i] = dgviewColumn.Name; 
       ++i; 
      } 

      Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2"); 
      headerColumnRange.Font.Bold = true; 
      headerColumnRange.Font.Color = 0xFF0000; 

      //headerColumnRange.EntireColumn.AutoFit(); 
      int rowIndex = 0; 

      for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++) 
      { 
       DataGridViewRow dgRow = dgView.Rows[rowIndex]; 

       for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++) 
       { 
        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value; 
       } 
      } 

      Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString()); 
      fullTextRange.WrapText = true; 
      fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; 
     } 
     else 
     { 
      string timeStamp = DateTime.Now.ToString("s"); 
      timeStamp = timeStamp.Replace(':', '-'); 
      timeStamp = timeStamp.Replace("T", "__"); 
      currentWorksheet.Cells[1, 1] = timeStamp; 
      currentWorksheet.Cells[1, 2] = "No error occured"; 
     } 

     using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog()) 
     { 
      exportSaveFileDialog.Title = "Select Excel File"; 
      exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx"; 

      if (DialogResult.OK == exportSaveFileDialog.ShowDialog()) 
      { 
       string fullFileName = exportSaveFileDialog.FileName; 
       // currentWorkbook.SaveCopyAs(fullFileName); 
       // indicating that we already saved the workbook, otherwise call to Quit() will pop up 
       // the save file dialogue box 

       currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue); 
       currentWorkbook.Saved = true; 
       MessageBox.Show("Exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
    finally 
    { 
     if (excelApp != null) 
     { 
      excelApp.Quit(); 
     } 
    } 
} 

但由於有超過20萬點的記錄,它的花費很長的時間來出口。有沒有更快的方法來做到這一點?

+0

這些鏈接可能會幫助你:[link1](http://stackoverflow.com/a/11742908/1135581)和[link2](http://www.codeproject.com/Articles/19284/ Export-large-data-from-Gridview-and-Datareader-to) – Rahul

回答

7

試試看看這個代碼。它比正常的互操作方法更快,也可以轉換成CSV,Excel可以輕鬆讀取它。

int cols; 
//open file 
StreamWriter wr = new StreamWriter("GB STOCK.csv"); 

//determine the number of columns and write columns to file 
cols = dgvStock.Columns.Count; 
for (int i = 0; i < cols - 1; i++) 
{ 
    wr.Write(dgvStock.Columns[i].Name.ToString().ToUpper() + ","); 
} 
wr.WriteLine(); 

//write rows to excel file 
for (int i = 0; i < (dgvStock.Rows.Count - 1); i++) 
{ 
    for (int j = 0; j < cols; j++) 
    { 
     if (dgvStock.Rows[i].Cells[j].Value != null) 
     { 
      wr.Write(dgvStock.Rows[i].Cells[j].Value + ","); 
     } 
     else 
     { 
      wr.Write(","); 
     } 
    } 

    wr.WriteLine(); 
} 

//close file 
wr.Close(); 
+0

該代碼將每行放入1 excell單元格中(MSVS 2005,.net2)。 – Vadim

-2

如何在C#中的asp.net中將GridView數據導出爲ex​​cel。 更多詳情click here

+3

請注意,[只有鏈接的答案](http://meta.stackoverflow.com/tags/link-only-answers/info)是不鼓勵的,所以答案應該是搜索解決方案的最終目標。而另一個引用的中途停留時間往往會隨着時間推移而過時)。請考慮在此添加獨立的摘要,並將鏈接保留爲參考。 – kleopatra

+0

你好先生檢查這個鏈接它是這個問題的答案 – Jquery

+0

你好,請閱讀我的最新評論中的鏈接:-) – kleopatra

相關問題