如何将大型excel文件导入数据表

本文关键字:文件 导入 数据表 excel 大型 | 更新日期: 2023-09-27 18:28:33

我有一个包含500列的Excel文件。我正在使用OLEDB将其导入DataTable。但是DataTable只包含前255列。我不明白为什么其余的列没有导入。

我的代码是

public DataTable ToDataTable()
{
    DataSet dsEmpMaster = new DataSet();
    DataTable dtEmpMaster = null;
    string strConnectionString;
    string strSql;
    string FileNameWithPath = String.Format("{0}''{1}", System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), _FileName);
    try
    {
        dtEmpMaster = new DataTable();
        strConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", FileNameWithPath);
        strSql = String.Format("SELECT * FROM [{0}$]", _SheetName);
        OleDbDataAdapter adpMasterData = new OleDbDataAdapter(strSql, strConnectionString);
        adpMasterData.Fill(dsEmpMaster);
        dtEmpMaster = dsEmpMaster.Tables[0];
        adpMasterData.Dispose();
    }
    catch (Exception ex)
    {
        _ExcelError = ex.Message;
    }

如何将大型excel文件导入数据表

OLEDB不能支持>256列,请参阅此解决方法。

        var file_path = @"D:'doc'excel.xlsx";
        Microsoft.Office.Interop.Excel.Application xlApp =
            new Microsoft.Office.Interop.Excel.ApplicationClass();
        // Disabling messageboxes to prevent losing control on Excel app
        xlApp.DisplayAlerts = false;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook =
            xlApp.Workbooks.Open(file_path, 0, false, 5, "", "", true,
                Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "'t", false, false, 0, true, 1, 0);
        xlWorkBook.DoNotPromptForConvert = true;
        for (var k = 1; k <= xlWorkBook.Worksheets.Count; k++)
        {
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet =
                (Microsoft.Office.Interop.Excel.Worksheet) this.xlWorkBook.Worksheets.get_Item(k);
            int cCnt = xlWorkSheet.Cells.Count;
            // processing all cells used, but can call named ranges
            Microsoft.Office.Interop.Excel.Range range = xlWorkSheet.UsedRange;
            for (var rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    Microsoft.Office.Interop.Excel.Range rng =
                        (Microsoft.Office.Interop.Excel.Range) range.Cells[rCnt, cCnt];
                    // do something with range
                }
            }
        }

但正如在该线程中提到的,Interop可能对您的需求来说太慢了,我个人还没有使用过它,但它可能值得一看ExcelDataReader 之类的东西

edit:正在修复链接的代码格式