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;

}

}

}

相关推荐
m***667310 分钟前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
Avalon71213 分钟前
Unity中自定义协程的实现
游戏·unity·c#·游戏引擎
e***582316 分钟前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
IMPYLH16 分钟前
Lua 的 select 函数
java·开发语言·笔记·后端·junit·游戏引擎·lua
LateFrames20 分钟前
WinUI3 模拟 iPad 高级感动画:高斯模糊渐变 + 侧边划入
c#·winui3
JienDa21 分钟前
JienDa聊PHP:知乎仿站实战中PHP框架的协同架构方略
开发语言·架构·php
hashiqimiya22 分钟前
android将json数据传递到后端springboot
java·开发语言
lijiatu1008623 分钟前
[C++] 上锁、解锁、获取锁、释放锁的区别
开发语言·c++
D***t13126 分钟前
Swift在iOS中的多任务处理
开发语言·ios·swift
mit6.82428 分钟前
C 语言仓库引入 Rust: MCUboot 为例
开发语言·rust