C#使用ExcelDataReader读取Excel并返回DataTable类

2023-12-13 12:02:09

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;
??????? }
??? }
}

文章来源:https://blog.csdn.net/qq_33790894/article/details/134534814
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。