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;

}

}

}

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