2012-02-22 67 views
1

我有一個由6個表組成的數據集。當我將它們放入我的方法中時,它在第一張桌子上完美無瑕地工作。但是,我注意到在第二個表中第二行(在列下)是空白的,然後顯示錶格數據。這一點對於表3來說也是一樣的,只有這兩行是空白的。隨着每個剩餘表格的建立,這會增加空白行。我確認表格本身沒有這些空行。我希望在這裏有人會這麼友好地看看這段代碼,讓我知道這是什麼原因。將數據表導出到Excel工作表 - 創建空行時

public Excel.Application PrepareForExport(System.Data.DataSet ds) 
{ 
    object missing = System.Reflection.Missing.Value; 
    Excel.Application excel = new Excel.Application(); 
    Excel.Workbook workbook = excel.Workbooks.Add(missing); 
    int k = 0; 
    int tableCount = 6; 
    for (int j = 0; j < tableCount; j++) 
    { 
     Excel.Worksheet newWorksheet; 
     newWorksheet = (Excel.Worksheet)excel.Worksheets.Add(missing, missing, missing, missing); 


     System.Data.DataTable dt = new System.Data.DataTable(); 
     dt = ds.Tables[j]; 
     // name sheet 
     string tableName = string.Empty; 

     switch (j) 
     { 
      case 0: 
       tableName = "TEST1"; 
       break; 
      case 1: 
       tableName = "TEST2"; 
       break; 
      case 2: 
       tableName = "TEST3"; 
       break; 
      case 3: 
       tableName = "TEST4"; 
       break; 
      case 4: 
       tableName = "TEST5"; 
       break; 
      case 5: 
       tableName = "TEST6"; 
       break; 
      default: 
       tableName = "INVALID"; 
       break; 
     } 

     newWorksheet.Name = tableName; 


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


     int iRow = 0 + k; 
     foreach (DataRow r in dt.Rows) 
     { 
      iRow++; 


      for (int i = 1; i < dt.Columns.Count + 1; i++) 
      { 
       if (iRow == 1) 
       { 
        // Add the header the first time through 
        excel.Cells[iRow, i] = dt.Columns[i - 1].ColumnName; 
       } 

       if (r[1].ToString() != "") 
       { 
        excel.Cells[iRow + 1, i] = r[i - 1].ToString() + " - " + dt.Columns.Count; 
       } 
      } 

     } 
     k++; 
    } 
    return excel; 
} 
+0

請不要在「C#」等前加上標題。這就是標籤的用途。 – 2012-02-22 23:42:41

+0

哎呀,對不起! :( – 2012-02-23 00:51:53

+0

沒問題,現在你知道了 – 2012-02-23 00:53:48

回答

0

我認爲這是你的int k變量和iRow是問題。
您設置

int k = 0; 

外循環的通過表。
然後在循環裏你有

int iRow = 0 + k; 

,然後你在循環的末尾增加ķ。 因此,對於第一個表,你有iRow = 0;第二個表,iRow = 1;第三張表,iRow = 2.

+0

是的!就是這樣!謝謝! :) – 2012-02-23 00:57:10