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;

}

}

}

相关推荐
.痞老板.26 分钟前
java ee--计算机是如何工作的
java·开发语言·java-ee
奇树谦29 分钟前
Qt Quick 图片加载与 GPU 纹理机制详解:QImage、QQuickTextureFactory、QSGTexture 与异步加载
开发语言·qt·系统架构
青梅味猪大肠37 分钟前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统
宝桥南山1 小时前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=02 小时前
C# 中 Lambda、Linq 与 Expression
c#·linq
starzy19902 小时前
深入理解Scala可变Map:动态构建场景下的性能与设计权衡
开发语言·scala
zhanghaha13143 小时前
C# 系列教程_7 判断语句(分支)保姆级精讲
开发语言·c#
apcipot_rain3 小时前
C++转Java日记(02)
java·开发语言·c++
杜 硕3 小时前
从零开始的C++生活——第七讲——02
开发语言·c++·生活
zhanghaha13143 小时前
C# 系列教程_8 循环语句 保姆级精讲(面向新手)
开发语言·c#