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;

}

}

}

相关推荐
hello 早上好5 分钟前
07_JVM 双亲委派机制
开发语言·jvm
前端程序猿i24 分钟前
第 8 篇:Markdown 渲染引擎 —— 从流式解析到安全输出
开发语言·前端·javascript·vue.js·安全
kronos.荒25 分钟前
滑动窗口:寻找字符串中的字母异位词
开发语言·python
_codemonster36 分钟前
java web修改了文件和新建了文件需要注意的问题
java·开发语言·前端
甄心爱学习1 小时前
【python】list的底层实现
开发语言·python
独自破碎E1 小时前
BISHI41 【模板】整除分块
java·开发语言
hewence11 小时前
Kotlin CoroutineContext 详解
android·开发语言·kotlin
IvanCodes1 小时前
七、C语言指针
c语言·开发语言
寻寻觅觅☆1 小时前
东华OJ-基础题-120-顺序的分数(C++)
开发语言·c++·算法
Myosotis5131 小时前
作业 第三次
开发语言·python