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;

}

}

}

相关推荐
2601_9491465313 分钟前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧18 分钟前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX24 分钟前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010331 分钟前
C++课后习题训练记录Day98
开发语言·c++
懒人咖1 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
猫头虎1 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE2 小时前
PHP纹路验证码
开发语言·php
仟濹2 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥2 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
Re.不晚2 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言