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;

}

}

}

相关推荐
njsgcs1 小时前
拆分多实体到装配体 solidworks c#
c#
techdashen1 小时前
Cloudflare 如何把一个大型代理拆成三个小服务来提升可靠性
开发语言·rust
geovindu2 小时前
go: Chain of Responsibility Pattern
开发语言·设计模式·golang·责任链模式
十五年专注C++开发2 小时前
WaitingSpinnerWidget: 一个高度可配置的自定义Qt等待加载动画组件
开发语言·c++·qt·waitingspinner
苍煜2 小时前
ThreadPoolExecutor线程池终极全解:同步异步判定+SpringBoot生产实战
java·开发语言·spring boot
何以解忧唯有撸码2 小时前
C# 视频录制监控系统
c#·winform
fengfuyao9852 小时前
EWT(经验小波变换)MATLAB实现与应用
开发语言·matlab
MasonYyp7 小时前
基于Python可定制开发的智能体框架
开发语言·python
橘颂TA7 小时前
【Linux】读写锁
大数据·linux·开发语言·c++·读写锁
lv__pf7 小时前
集合框架1
java·开发语言