2012-02-22 68 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