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;

}

}

}

相关推荐
穗余几秒前
Rust——impl是什么意思
开发语言·后端·rust
程序员大辉1 分钟前
开源LibreOffice(Office办公套件)下载完整安装教程
开发语言·microsoft·c#
yngsqq2 分钟前
运行c#脚本
开发语言·数据库·c#
代码羊羊3 分钟前
Rust模式匹配
开发语言·后端·rust
Wild_Pointer.8 分钟前
项目实战:编写CMakeLists管理Qt+OpenCV项目
开发语言·c++·qt
莫逸风9 分钟前
【java-core-collections】集合框架深度解析
java·开发语言
geovindu11 分钟前
go: Bridge Pattern
开发语言·设计模式·golang·软件构建·桥接模式
Fate_I_C14 分钟前
Kotlin 为什么是 Android 开发的首选语言
android·开发语言·kotlin
格鸰爱童话18 分钟前
python录音转文字
开发语言·python
常利兵19 分钟前
Kotlin 助力 Android 启动“大提速”
android·开发语言·kotlin