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;

}

}

}

相关推荐
下北沢美食家9 分钟前
Express框架入门
开发语言·javascript·express
遥望九龙湖20 分钟前
打包动态库
开发语言·c++·visualstudio
m0_5312371734 分钟前
C语言-编程实例2
c语言·开发语言
dreams_dream35 分钟前
Python 的 GIL 是什么?有什么影响?
开发语言·python
麻瓜pro1 小时前
【迭代】高性能c++实时对话系统e2e_voice
开发语言·c++·onnxruntime·端到端语音
zjxtxdy1 小时前
C语言(续)
c语言·开发语言
无尽的沉默1 小时前
Thymeleaf 基本语法和表达式
java·开发语言
Coder_Boy_1 小时前
Java后端核心技术体系全解析(个人总结)
java·开发语言·spring boot·分布式·spring cloud·中间件
zh_xuan1 小时前
kotlin Flow的用法2
android·开发语言·kotlin·协程·flow·被压
南部余额1 小时前
函数式接口 Lambda 表达式好搭档:Predicate、Function、Consumer、Supplier
java·开发语言·consumer·lambda·function·predicate·supplier