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;

}

}

}

相关推荐
2501_9445215910 分钟前
Flutter for OpenHarmony 微动漫App实战:动漫卡片组件实现
android·开发语言·javascript·flutter·ecmascript
superman超哥23 分钟前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
easyboot25 分钟前
C#使用pythonnet简单示例
开发语言·python·c#
晚霞的不甘30 分钟前
Flutter 布局核心:构建交互式文档应用
开发语言·javascript·flutter·elasticsearch·正则表达式
少控科技39 分钟前
QT新手日记 030
开发语言·qt
小此方1 小时前
Re:从零开始的 C++ STL篇(三)string的疑难问题详细解析:深拷贝,写时拷贝,三个swap
开发语言·c++
Linux猿1 小时前
基于Python的图书管理系统(可执行源码+详细报告+详细注释+运行步骤)
开发语言·python·毕业设计·课程设计·管理系统·图书管理系统项目
lanbing1 小时前
在Mac OS系统中安装Go语言环境教程
开发语言·后端·golang
sensen_kiss1 小时前
Python安装与环境配置全程详细教学(包含Windows版和Mac版)
开发语言·python·pycharm
程序员敲代码吗1 小时前
嵌入式C++开发注意事项
开发语言·c++·算法