C#使用ExcelDataReader读取Excel并返回DataTable类

using ExcelDataReader;
using System;
using System.Data;
using System.IO;

public class ExcelReader
    {
        public static DataTable GetExcelDatatable(string fileUrl)
        {

            using (var stream = File.Open(fileUrl, FileMode.Open, FileAccess.Read))
            {
                IExcelDataReader reader;

                if (fileUrl.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (fileUrl.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }
                else
                {
                    throw new Exception("Invalid Excel file format");
                }

                DataSet ds = new DataSet();

                ds.Tables.Add(ReadData(reader));

                return ds.Tables[0];

            }

        }


        static DataTable ReadData(IExcelDataReader reader)
        {
            DataTable dt = new DataTable();
            reader.Read();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                dt.Columns.Add(reader.GetValue(i).ToString());
            }
            while (reader.Read())
            {
                DataRow row = dt.NewRow();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    row[i] = reader.GetValue(i);
                }
                dt.Rows.Add(row);
            }

            return dt;
        }
    }
}

你可能感兴趣的:(c#,开发语言)