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;
??????? }
??? }
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!