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;

}

}

}

相关推荐
ONE_PUNCH_Ge2 小时前
Go 语言变量
开发语言
幼稚园的山代王2 小时前
go语言了解
开发语言·后端·golang
晚风残2 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
Panda__Panda2 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
满天星83035772 小时前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
weixin_456904273 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
ss2733 小时前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
麦麦鸡腿堡4 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里4 小时前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
Tiger_shl4 小时前
C# 预处理指令 (# 指令) 详解
开发语言·c#