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.Tables0;

}

}

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++)

{

rowi = reader.GetValue(i);

}

dt.Rows.Add(row);

}

return dt;

}

}

}

相关推荐
卡卡~~2 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
qq_406981033 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust
学逆向的3 小时前
C 多文件开发
c语言·开发语言·网络安全
布吉岛的石头3 小时前
Java 程序员第 50 阶段3:数据工程:预训练语料清洗与去重
java·开发语言·人工智能·深度学习·transformer
benchmark_cc3 小时前
QuantDash 安装成功后,如何验证 Python 环境可以正常导入 SDK?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
学逆向的3 小时前
C 内存属性
c语言·开发语言·算法·网络安全
阿松爱学习4 小时前
【Unity开发】Unity长截图功能实现
unity·c#·游戏引擎
HAPPY酷5 小时前
C++ 自定义内存池优化点云处理:从裸指针到 RAII 自动回收
开发语言·c++
梦帮科技5 小时前
量子纠缠网络与量子隐形传态攻防:量子中继器信道串扰、纠缠态保真度降解与量子路由劫持
开发语言·网络·人工智能·算法·自动化·php