2014-02-14 29 views
0

如何從所有Excel表單中返回單個數據表,但我已寫入此方法的所有代碼,但是當多於一個表單讀取數據時從第2張,第3張等將其插入到第1張紙張欄中。請糾正這個問題,它會幫助很多想使用interop.excel COM讀取所有excel表格的人,這是非常好的工具,因爲ado.net讀取會產生版本兼容性問題。如何使用Interop.Excel庫從所有Excel表單返回單個數據表

public System.Data.DataTable SetOne(string ExcelFilePath) 
{  
    System.Data.DataTable table = new System.Data.DataTable(); 
    Microsoft.Office.Interop.Excel.Application app = new  Microsoft.Office.Interop.Excel.Application(); 
    Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(ExcelFilePath, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing); 
      int NoOfSheetRows=0; 
    foreach (Worksheet item in app.Worksheets) 
    { 
     string sheetname = item.Name; 
     Worksheet sheet = (Worksheet)wb.Sheets[sheetname]; 

     Range excelRange = sheet.UsedRange; 
     string fileRange = sheet.UsedRange.Address; 
     string filecolums = fileRange.Substring(6, 1); 
     List<string> str = new List<string>(); 
     int cntr = 0; 

     foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows) 
     { 
      int rowNumber = row.Row; 
      string[] A4D4 = this.GetRange("A" + rowNumber + ":" + filecolums + "" + rowNumber + "", sheet); 

      if (rowNumber.Equals(1)) 
      { 
       foreach (var itm in A4D4) 
       { 
        if (table.Columns.Contains(itm)==false) 
        { 
         table.Columns.Add(itm); 
         str.Add(itm); 
         cntr++; 
        } 
        else 
        { 
         table.Columns.Add(itm + ".."); 
         str.Add(itm); 
         cntr++; 
        } 
       } 
      } 
      else 
      { 
       DataRow drow; 
       drow = table.NewRow(); 
       drow.ItemArray = A4D4; 
       //table.Rows.InsertAt(drow, NoOfSheetRows); 
       table.Rows.Add(drow); // This is Area where the Problem is created the the sheet 2,3,4 and so forth data is inserted to 1st Sheet Columns 
      } 
     } 
     NoOfSheetRows += cntr; 
    } 
    return table; 
} 

public string[] GetRange(string range, Worksheet excelWorksheet) 
{ 
    Microsoft.Office.Interop.Excel.Range workingRangeCells = 
     excelWorksheet.get_Range(range, Type.Missing); 
    System.Array array = (System.Array)workingRangeCells.Cells.Value2; 
    string[] arrayS = array.OfType<object>().Select(o => o.ToString()).ToArray(); 
    return arrayS; 
} 
+0

使用interop.excel意味着您已經在Web服務器上安裝了Microsoft Excel(例如)。微軟表示微軟Office不能用於服務器端,它不是爲它設計的(它會崩潰,消耗大量內存並凍結應用程序池)。 – bdn02

+0

爲了上帝的緣故,使用Interop進行此類操作。你不使用錘子來耕田,而是在Web服務器上使用互操作性更加錯誤。 使用類似EPPLUS,aspose.cells(xls支持)或其他bazillion其他庫之一的庫。 –

+0

@ bdn02我使用的是桌面應用程序或Web,因此不需要Web服務器。因此Interop適用於獨立系統,與創建兼容性問題的ado.net比較起來。但是,我的問題只是在DataTable中組織數據,因爲我已經從Excel文件中讀取數據了。@ Christian Sauer我錯了嗎 –

回答

1

我會推薦EPPLUS - 這是一個設計用於讀/寫xlsx/xlsm文件的庫。它非常快速,免費,比Interop更強大。

相關問題