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;

}

}

}

相关推荐
CodeByV几秒前
【C++】C++11:其他重要特性
开发语言·c++
2501_941111339 分钟前
C++代码重构实战
开发语言·c++·算法
爱装代码的小瓶子15 分钟前
【c++知识铺子】相对简单的容器适配器双生子-stack和queue(STL)
开发语言·c++
豐儀麟阁贵27 分钟前
6.2 Object类
java·开发语言·python
MichaelIp28 分钟前
Python同步vs异步性能对比实验-2
开发语言·python·性能优化·可用性测试
white-persist41 分钟前
二进制movl及CTF逆向GDB解析:Python(env)环境下dbg从原理到实战
linux·服务器·开发语言·python·网络安全·信息可视化·系统安全
脏脏a42 分钟前
类和对象(下):初始化列表、静态成员与友元深度解析
开发语言·c++
lkbhua莱克瓦2442 分钟前
Java进阶——集合进阶(MAP)
java·开发语言·笔记·github·学习方法·map
代码狂想家43 分钟前
Rust 命令行密码管理器工具开发
开发语言·rust·php