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;

}

}

}

相关推荐
闲猫几秒前
LangChain / Core components / Models
开发语言·python·langchain
-银雾鸢尾-1 小时前
C#中的索引器
开发语言·c#
Qlittleboy2 小时前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Aurorar0rua2 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
en.en..2 小时前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
兰令水2 小时前
hot100【acm版】【2026.7.18打卡-java版本】
java·开发语言·算法
cui_ruicheng2 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
就叫飞六吧3 小时前
子页面和dialog案例
开发语言·javascript·ecmascript
geovindu3 小时前
CSharp: Decorator Pattern
开发语言·后端·c#·装饰器模式·结构型模式
倒流时光三十年3 小时前
Logback 系列(3):三大核心组件 Logger / Appender / Encoder
java·开发语言·logback