Convert xls and xlsx to Datatable in C#

本秂侑毒 提交于 2021-02-18 12:10:29

问题


I am working in converting ths xls and xlsx to datatable in c#. I have used this code.

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

In case of xls, its working fine. Whenever i used xlsx its not working. Its giving 'Object Reference' error.

Whether there are any other way to convert both the xls and xlsx to datatable. I am not interested in using 'Microsoft.Jet.OLEDB'....


回答1:


This is the answer.

For importing xlsx,

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

For importing xls,

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);



回答2:


Add EPPlus dll from nudget. Add excel file content to memory stream. Then you can use as per below code.

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



回答3:


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


来源:https://stackoverflow.com/questions/25808851/convert-xls-and-xlsx-to-datatable-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!