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;

}

}

}

相关推荐
NiNi_suanfa3 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码3 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent3 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
妖灵翎幺3 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
Halo_tjn4 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen4 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans4 小时前
pycharm之gitignore设置
开发语言·python·pycharm
别叫我->学废了->lol在线等5 小时前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
张人玉5 小时前
技术开发文档:MES 系统与西门子 PLC 通信软件集成方案
https·c#·plc·mes系统·西门子s7
VX:Fegn08955 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计