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;

}

}

}

相关推荐
青槿吖12 小时前
告别RestTemplate!Feign让微服务调用像点外卖一样简单
java·开发语言·分布式·spring cloud·微服务·云原生·架构
chxii12 小时前
lua 下载和配置环境变量
开发语言·lua
froginwe1112 小时前
Bootstrap4 导航栏
开发语言
虾神说D12 小时前
[AI时代码农生存指南]Rust编写CLI 01. CLI的复古轮回
开发语言·人工智能·rust
Kurisu_红莉栖12 小时前
c++的复习——多态
开发语言·c++
geovindu12 小时前
go: Prototype Pattern
开发语言·设计模式·golang·原型模式
pearlthriving12 小时前
STL容器及其底层
开发语言·c++·算法
唐青枫12 小时前
C#.NET TaskCompletionSource 深入解析:手动控制 Task、桥接回调事件与实战避坑
c#·.net
chao18984412 小时前
具有飞行约束的无人机MPC MATLAB实现
开发语言·matlab·无人机
张人玉12 小时前
VisionPro 药物检测工具 学习笔记
算法·c#·机器视觉·vsionpro