2012-02-16 45 views
1

我使用C#和Interop.Excel.Range爲工作表返回使用的列的範圍,並將使用的列和行寫入到datagrid視圖。一些列正在返回空白/空。如何跳過一個範圍內的空白列?

Microsoft.Office.Interop.Excel.Range excelRange = wWorksheet.UsedRange; 

TabPage wTabPage = new TabPage(wWorksheet.Name.ToString()); 
DataGridView wDGV = new DataGridView(); 
wDGV.Dock = DockStyle.Fill; 
wTabPage.Controls.Add(wDGV); 
Sheets_TabControl.TabPages.Add(wTabPage); 

DataTable dt = new DataTable(); 
DataRow wNewRow = null; 

for (int i = 0; i < excelRange.Columns.Count; i++) 
{ 
    dt.Columns.Add(new DataColumn(i.ToString(), typeof(string))); 
} 

string wValue = string.Empty; 
Microsoft.Office.Interop.Excel.Range wRange = null; 

for (int wRowIndex = 1; wRowIndex <= skipRows; wRowIndex++) 
{ 
    wNewRow = dt.NewRow(); 

    foreach (DataColumn wColumn in dt.Columns) 
    { 
     wRange = excelRange.Cells[wRowIndex, wColumn.Ordinal + 1]; 

     if (wRange != null) 
     { 
      if (wRange.Value2 != null) 
      { 
       wValue = wRange.Value2.ToString(); 

       if (!string.IsNullOrEmpty(wValue)) 
       { 
        wNewRow.SetField(wColumn, wValue); 
       } 
      } 

     } 
    } 

    dt.Rows.Add(wNewRow) 
} 

wDGV.DataSource = dt; 

有沒有辦法在寫入那些包含數據的列時跳過或忽略任何空白的列?

感謝您的幫助!

回答

0

這個關鍵是使用VBA工作表函數​​,它返回一個值,指示給定範圍內有多少個單元格有數據。基於此,您可以決定是否在您的DataTable中創建一列。

由於您的表格列和Excel範圍列現​​在不同步,因此您需要使用您在代碼中設置的列名稱作爲相應Excel範圍列的索引。

因此,正在調整你的代碼給出:

Microsoft.Office.Interop.Excel.Range excelRange = wWorksheet.UsedRange; 

TabPage wTabPage = new TabPage(wWorksheet.Name.ToString()); 
DataGridView wDGV = new DataGridView(); 
wDGV.Dock = DockStyle.Fill; 
wTabPage.Controls.Add(wDGV); 
Sheets_TabControl.TabPages.Add(wTabPage); 

DataTable dt = new DataTable(); 
DataRow wNewRow = null; 

// New code to create DataTable columns 

for (int i = 1; i <= excelRange.Columns.Count; i++) 
{ 
    // If the current column of cells does not contain any data, then don't add a column to the datatable 

    if (xlSpreadsheet.App.WorksheetFunction.CountA(excelRange.Cells[Missing.Value, i]) != 0) 
    { 
     dt.Columns.Add(new DataColumn(i.ToString(), typeof(string))); 
    } 
} 

string wValue = string.Empty; 
Microsoft.Office.Interop.Excel.Range wRange = null; 

for (int wRowIndex = 1; wRowIndex <= excelRange.Rows.Count; wRowIndex++) 
{ 
    wNewRow = dt.NewRow(); 

    foreach (DataColumn wColumn in dt.Columns) 
    { 
     // Parse the column number we stored earlier as the column name 

     int colNumber = 0; 

     if (int.TryParse(wColumn.ColumnName, out colNumber)) 
     { 
      // We use the parsed column number to index the column in the Excel range 

      wRange = excelRange.Cells[wRowIndex, colNumber]; 

      if (wRange != null) 
      { 
       if (wRange.Value2 != null) 
       { 
        wValue = wRange.Value2.ToString(); 

        if (!string.IsNullOrEmpty(wValue)) 
        { 
         wNewRow.SetField(wColumn, wValue); 
        } 
       } 
      } 
     } 
    } 

    dt.Rows.Add(wNewRow) 
} 

wDGV.DataSource = dt;