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;

}

}

}

相关推荐
sunly_4 分钟前
Go 切片详解
开发语言·oracle·golang
fengkai454518 分钟前
Python对接LangChain智能体开发(Tool工具调用与 Agent智能体)
运维·开发语言·python·langchain·llm·ai agent·tool
随流寻影1 小时前
利用 C++ 实现二叉搜索树的增删查
开发语言·c++
总要学点什么2 小时前
第128篇:镜头光晕与高光——把逆光太阳晕成会躲山的光斑
开发语言·javascript·数码相机·microsoft·材质·cesium
Escalating_xu2 小时前
【COZE实战】插件与知识库(三):让智能体会查资料,也会使用工具
开发语言·网络·人工智能·ai
学逆向的2 小时前
C++多态 汇编分析
开发语言·汇编·c++·网络安全
阿凤212 小时前
学习java---流程控制篇
java·开发语言·学习
Code_Solitude3 小时前
c语言:期末最后一道大题模拟
c语言·开发语言
李松桃3 小时前
Python爬虫基础
开发语言·爬虫·python·get请求使用方法·post请求使用方法
weixin_307779133 小时前
Python用正则把 SQL 关键字整词匹配后转成小写
开发语言·python·sql·算法