在C#中将xls和xlsx转换为Datatable

时间:2014-09-12 12:56:32

标签: c#-4.0

我正在努力将xls和xlsx转换为c#中的datatable。我使用过这段代码。

public DataTable ReadDataExcel(string filepath)
    {
        FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        excelReader.IsFirstRowAsColumnNames = true;
        DataSet result = excelReader.AsDataSet();
        DataTable dt = new DataTable();
        dt = result.Tables[0];
        return dt;
    }

对于xls,它的工作正常。每当我使用xlsx它不工作。它给出了对象参考'错误。

是否有任何其他方法可以将xls和xlsx转换为datatable。我对使用不感兴趣 ' Microsoft.Jet.OLEDB' ...

3 个答案:

答案 0 :(得分:3)

这就是答案。

导入xlsx,

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

导入xls,

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

答案 1 :(得分:1)

从nudget添加 EPPlus dll。将excel文件内容添加到内存流。然后,您可以按照以下代码使用。

ExcelPackage package = new ExcelPackage(stream);
ExcelWorksheet workSheet = package.Workbook.Worksheets.First();

答案 2 :(得分:-2)

 public static DataTable MakeDataTablefromxls(string _path, string password = "")
    {
        DataTable dt = new DataTable();
        try
        {
            log.Info("MakeDataTablefromxls : Excel scraping started");
            xlsApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlsApp == null)
            {
                return null;
            }
            wb = xlsApp.Workbooks.Open(_path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true);
            sheets = wb.Worksheets;
            ws = (Excel.Worksheet)sheets.get_Item(1);
            range = ws.UsedRange;
            if (wb.ProtectStructure)
            {
                wb.Unprotect(password);
            }

            object[,] values = (object[,])range.Cells.Value;

            //To Create columns of DataTable as per column  range in xlxs sheet
            for (int i = 1; i <= values.GetLength(1); i++)
            {
                dt.Columns.Add("F" + (i));
            }

            //To Create rows of DataTable as per column  range in xlxs sheet
            for (int i = 2; i < values.GetLength(1); i++)
            {
                DataRow row = dt.NewRow();
                for (int j = 1; j < values.GetLength(1); j++)
                {
                    row[j - 1] = values[i, j];// assigning Data from object array to data Datarow 
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
        catch (Exception ex)
        {
            log.Error("MakeDataTablefromxls : error : ", ex);
            return null;
        }
        finally
        {
            wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            xlsApp.Quit();
            GC.Collect();
            if (range != null) Marshal.FinalReleaseComObject(range);
            if (wb != null) Marshal.FinalReleaseComObject(wb);
            if (sheets != null) Marshal.FinalReleaseComObject(sheets);
            if (xlsApp != null) Marshal.FinalReleaseComObject(xlsApp);
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            dt.Dispose();
            log.Info("MakeDataTablefromxls : Excel scraping completed");
        }
    }