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;

}

}

}

相关推荐
郝学胜-神的一滴4 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
zbguolei5 小时前
第001篇 · 算盘与差分机
开发语言·php
ZHOUPUYU5 小时前
PHP 8.4 新特性实战指南:从属性钩子到异步编程
开发语言·php
SummerJokes5 小时前
Java 多线程专项实验|两种创建线程方式、synchronized 线程同步、银行存取款实战
java·开发语言·python
艾派森6 小时前
Python帕累托分析实战:用二八法则找出贡献80%营收的核心商品
android·开发语言·python
xyphf_和派孔明6 小时前
第九章: 上下文工程五大策略与六大模块交叉矩阵纵览
java·开发语言
纪念 2296 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
向科→向总工→空间动态计系统6 小时前
剃刀明盒:几何与时序双验证
大数据·开发语言·人工智能·python
杜 硕7 小时前
从零开始的C++生活——第十六讲
开发语言·数据结构·c++·生活