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;

}

}

}

相关推荐
星火开发设计19 小时前
C++ multiset 全面解析与实战指南
开发语言·数据结构·c++·学习·set·知识
lsx20240619 小时前
Eclipse 添加书签
开发语言
易营宝19 小时前
高效的跨境电商广告优化系统:易营宝广告投放实操指南
大数据·开发语言·人工智能·php
superman超哥20 小时前
路由的艺术:Rust Web 框架中的高效匹配与类型安全提取
开发语言·rust·编程语言·rust web框架·rust路由
hqwest20 小时前
码上通QT实战22--趋势页面01-准备图表对象
开发语言·qt·qpainter·qss·painevent·qt绘图事件
hqwest20 小时前
码上通QT实战23--趋势页面02-图表模拟数据
开发语言·qt·qpainter·qt绘图·绘制曲线
Echo缘20 小时前
关于在.cpp文件中包含c的头文件,编译报错问题
c语言·开发语言
人道领域20 小时前
【零基础学java】(反射)
java·开发语言
ghie909020 小时前
GPS抗干扰算法MATLAB实现
开发语言·算法·matlab
ytttr87321 小时前
基于MATLAB解决车辆路径问题(VRP)
开发语言·matlab