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.Tables0;

}

}

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++)

{

rowi = reader.GetValue(i);

}

dt.Rows.Add(row);

}

return dt;

}

}

}

相关推荐
淡海水7 小时前
02-03-原理篇-大对象堆
unity·c#·游戏引擎·.net·gc
H.莓飛7 小时前
【数据结构】栈
linux·开发语言·数据结构·算法·centos
无糖可乐没有灵魂7 小时前
用一篇文章来精通“进程/线程/协程/锁“多并发任务
开发语言·php
2601_962885727 小时前
如何用 Python 分析股票的日历效应?(星期效应与月份效应,附数据挖掘陷阱)
开发语言·python·数据挖掘
“AI国潮设计-小江”7 小时前
Python实战 | SDXL批量生成“带炸英歌”国潮IP:从海报到门店落地(附核心Prompt与授权思路)
开发语言·人工智能·python·prompt·aigc
字节渡客7 小时前
PHP项目复盘:foreach 引用残留造成的诡异数据错乱
开发语言·php
我就是不信7 小时前
深入理解 Python 虚拟机:字典(dict)的优化
开发语言·python·哈希算法
艾莉丝努力练剑7 小时前
【QT】系统相关:多线程QThread基础
开发语言·网络·c++·qt·学习·大模型
ysu_03148 小时前
uv实战指南-从Python版本虚拟环境到pyproject依赖管理
开发语言·python·pip·uv·虚拟环境·包管理·依赖管理