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;

}

}

}

相关推荐
7ioik14 小时前
新增的类以及常用的方法有哪些?
java·开发语言·python
无限进步_14 小时前
深入理解顺序表:从原理到完整实现
c语言·开发语言·数据结构·c++·算法·链表·visual studio
繁华似锦respect14 小时前
C++ 无锁队列(Lock-Free Queue)详细介绍
linux·开发语言·c++·windows·visual studio
专注API从业者14 小时前
Node.js/Python 调用淘宝关键词搜索 API:从接入到数据解析完整指南
开发语言·数据结构·数据库·node.js
liu****14 小时前
九.操作符详解
c语言·开发语言·数据结构·c++·算法
人得思变~谁会嫌自己帅呢?14 小时前
Java中的类加载器工作原理
java·开发语言
MediaTea14 小时前
Python 编程B17:文件(二)
开发语言·python
西游音月14 小时前
(10)功能实现:Qt实战项目之新建项目对话框
开发语言·qt
w***954914 小时前
在21世纪的我用C语言探寻世界本质——字符函数和字符串函数(2)
c语言·开发语言
ironinfo14 小时前
C#性能优化随记
开发语言·性能优化·c#