如何使用Interop.Excel库从所有Excel表单返回单个数据表

时间:2014-02-14 12:33:09

标签: c#

如何从所有Excel表格中返回单个数据表,我已经为此方法编写了所有代码,但是当它读取多张表时,则会将第二张,第三张等表中的数据插入到第一张表中列。请更正此问题,它将帮助很多想要使用interop.excel COM阅读所有Excel工作表的人,这是一个非常好的工具,因为ado.net读取会产生版本兼容性问题。

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;
}

1 个答案:

答案 0 :(得分:1)

我推荐EPPLUS - 它是一个用于读/写xlsx / xlsm文件的库。它比Interop更快,更自由,更强大。