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;

}

}

}

相关推荐
渔舟小调6 分钟前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳8 分钟前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木8 分钟前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***54413 分钟前
如何在Dev-C++中使用Clang编译器
开发语言·c++
码界筑梦坊23 分钟前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
Cosmoshhhyyy1 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
棋子入局1 小时前
C语言制作消消乐游戏(2)
c语言·开发语言·游戏
布谷歌1 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
WangJunXiang61 小时前
GFS分布式文件系统
开发语言·php
民乐团扒谱机1 小时前
【微实验】基于matlab的音频提取与信号滤波处理
开发语言·matlab·音视频