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;

}

}

}

相关推荐
星火开发设计1 分钟前
类模板:实现通用数据结构的基础
java·开发语言·数据结构·c++·html·知识
bugcome_com2 分钟前
# C# 变量作用域详解
开发语言·c#
阿里嘎多学长2 分钟前
2026-02-13 GitHub 热点项目精选
开发语言·程序员·github·代码托管
汽车软件工程师00111 分钟前
vector autosar配置一个CAN接收报文,RTE层发现并未接收到信号,怎样查这个问题
开发语言·autosar
寻寻觅觅☆23 分钟前
东华OJ-基础题-122-循环数(C++)-难度难
开发语言·c++
Zachery Pole44 分钟前
JAVA_04_判断与循环
java·开发语言
懒惰成性的1 小时前
11.Java的String类
java·开发语言
傻啦嘿哟1 小时前
Python列表排序:用key参数掌控排序规则
java·开发语言
你的冰西瓜1 小时前
C++ STL算法——修改序列算法
开发语言·c++·算法·stl
三方测试小学徒1 小时前
GB/T 34946-2017《C#语言源代码漏洞测试规范》之整体解读
c#·cma·cnas·34946