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;

}

}

}

相关推荐
yue0081 分钟前
C#读取App.Config配置文件
开发语言·c#
武藤一雄3 分钟前
WPF 资源解析:StaticResource & DynamicResource 实战指南
微软·c#·.net·wpf·.netcore
武藤一雄4 分钟前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
hyl200127 分钟前
c++ SCIP求解整数规划模型
开发语言·c++
echome8887 分钟前
Python 装饰器详解:从入门到实战
开发语言·python
奇树谦8 分钟前
QMap 全面解析(Qt5 vs Qt6)
开发语言·qt
sqyno1sky8 分钟前
代码动态生成技术
开发语言·c++·算法
蓝天星空9 分钟前
C# .net闭源与Java开源框架的对比
java·c#·.net
中科三方9 分钟前
域名管理常见问题:添加域名解析多久生效?为什么不能马上生效?
开发语言·php
廖圣平10 分钟前
Drogon 现代化C ++高性能框架
android·c语言·开发语言