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;

}

}

}

相关推荐
一个帅气昵称啊1 天前
基于.NET AgentFramework开发OpenClaw智能体框架
人工智能·自然语言处理·c#·.net·openclaw
娇娇yyyyyy1 天前
QT编程(17): Qt 实现自定义列表模型
开发语言·qt
唐青枫1 天前
C#.NET SpinLock 深入解析:自旋锁原理、使用边界与性能取舍
c#·.net
ms_27_data_develop1 天前
Java枚举类、异常、常用类
java·开发语言
add45a1 天前
C++编译期数据结构
开发语言·c++·算法
岁岁种桃花儿1 天前
AI超级智能开发系列从入门到上天第四篇:AI应用方案设计
java·服务器·开发语言
Amnesia0_01 天前
C++中的IO流
开发语言·c++
2401_891482171 天前
C++模块化编程指南
开发语言·c++·算法
暮冬-  Gentle°1 天前
自定义类型转换机制
开发语言·c++·算法
2301_816651221 天前
嵌入式C++低功耗设计
开发语言·c++·算法