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;

}

}

}

相关推荐
SuperEugene几秒前
JS/TS 编码规范实战:Vue 场景变量 / 函数 / 类型标注避坑|编码语法规范篇
开发语言·javascript·vue.js
暮冬-  Gentle°几秒前
C++中的工厂方法模式
开发语言·c++·算法
.NET修仙日记7 分钟前
Acme.ReturnOh:让.NET API返回值处理更优雅,统一响应格式一步到位
c#·.net·webapi
乱世军军26 分钟前
把 Python 3.13 降级到 3.11
开发语言·python
本喵是FW26 分钟前
C语言手记2
c语言·开发语言
fy1216328 分钟前
GO 快速升级Go版本
开发语言·redis·golang
共享家952730 分钟前
Java入门(String类)
java·开发语言
0xDevNull36 分钟前
Spring Boot 循环依赖解决方案完全指南
java·开发语言·spring
bbq粉刷匠38 分钟前
Java--多线程--单例模式
java·开发语言·单例模式
dfafadfadfafa40 分钟前
嵌入式C++安全编码
开发语言·c++·算法