2017-07-11 23 views
0

我試圖從C#導出數據庫Excel中而是從數據庫中的第一行是不是在Excel中保存。出口從C#練成沒有顯示第一行從數據庫

private void exporttoexcel() 
{ 
    Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application(); 
    Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing); 
    Microsoft.Office.Interop.Excel._Worksheet worksheet = null; 

    try 
    { 
     worksheet = workbook.ActiveSheet; 
     worksheet.Name = "ExportedFromDatGrid"; 

     int cellRowIndex = 1; 
     int cellColumnIndex = 1; 

     //Loop through each row and read value from each column. 
     for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 
     { 
      for (int j = 0; j < dataGridView1.Columns.Count; j++) 
      { 
       // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
       if (cellRowIndex == 1) 
       { 
        worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText; 
       } 
       else 
       { 
        worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString(); 
       } 
       cellColumnIndex++; 
      } 
      cellColumnIndex = 1; 
      cellRowIndex++; 
     } 
    } 
    catch(Exception ex) 
    { 
    } 
} 

這裏是我使用的代碼。任何人都可以幫我嗎?我是編碼新手。

+0

有在服務器上安裝Excel並不總是最好的解決方案。 @Rick範登博世已經提供了一個很好的答案,並通過使用ClosedXML的替代解決方案。我想補充一點,Epplus也是一種選擇。 https://www.nuget.org/packages/EPPlus/ –

回答

0

你不是寫出來的數據,但只寫出列名時cellColumnIndex是1,跳過第一行。但是,在第一行已被處理後,行索引遞增。重構你的for循環看起來是這樣的:

// Add the column names 
var index = 0; 
foreach(var column in dataGridView1.Columns) 
{ 
    worksheet.Cells[0, index] = column.HeaderText; 
    index++; 
} 

//Loop through each row and read value from each column. 
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 
{ 
    for (int j = 0; j < dataGridView1.Columns.Count; j++) 
    { 
     // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
     worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString(); 
     cellColumnIndex++; 
    } 
    cellColumnIndex = 1; 
    cellRowIndex++; 
} 

請看看ClosedXML。它簡化了編寫代碼,並消除需要有要運行這個機器上安裝Excel。