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;

}

}

}

相关推荐
xb11329 分钟前
C#生产者-消费者模式
开发语言·c#
电商API&Tina10 分钟前
乐天平台 (Rakuten) 数据采集指南
大数据·开发语言·数据库·oracle·json
今晚打老虎z23 分钟前
解决SQL Server 安装运行时针对宿主机内存不足2GB的场景
sqlserver·c#
zhougl99628 分钟前
Java内部类详解
java·开发语言
Grassto29 分钟前
11 Go Module 缓存机制详解
开发语言·缓存·golang·go·go module
代码游侠38 分钟前
学习笔记——Linux内核与嵌入式开发3
开发语言·arm开发·c++·学习
怎么没有名字注册了啊1 小时前
C++ 进制转换
开发语言·c++
代码游侠1 小时前
C语言核心概念复习(二)
c语言·开发语言·数据结构·笔记·学习·算法
冰暮流星1 小时前
javascript之双重循环
开发语言·前端·javascript
墨月白1 小时前
[QT]QProcess的相关使用
android·开发语言·qt