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;

}

}

}

相关推荐
overmind几秒前
oeasy Python 114 在列表指定位置插入insert
开发语言·python
github.com/starRTC6 分钟前
Claude Code中英文系列教程34:再谈Skills
开发语言·c#·ai编程
毕设源码-赖学姐11 分钟前
【开题答辩全过程】以 基于Java的外卖点餐网站为例,包含答辩的问题和答案
java·开发语言
蜡笔羊驼30 分钟前
LALIC环境安装过程
开发语言·python·深度学习
codeJinger35 分钟前
【Python】基础知识
开发语言·python
lsx2024061 小时前
JavaScript Math(算数)详解
开发语言
csbysj20201 小时前
Debian Docker 安装指南
开发语言
ShineWinsu1 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list
Mr YiRan1 小时前
C++语言类中各个重要函数原理
java·开发语言·c++
chilavert3181 小时前
技术演进中的开发沉思-370:final 关键字(上)
java·开发语言