ExcelDataReader 是一个轻量级且高效的库,用于读取 .xlsx
和 .xls
文件中的数据。本文将详细介绍如何在 C# 项目中使用 ExcelDataReader 库,并提供多个示例来演示其功能。
在开始之前,确保以下环境准备就绪:
首先,通过 NuGet 包管理器安装 ExcelDataReader 库。您可以在 NuGet 包管理器控制台中运行下面的命令:
C#Install-Package ExcelDataReader
此外,还需要安装一个支持读取方式的包:
PowerShellInstall-Package ExcelDataReader.DataSet
File Type | Container Format | File Format | Excel Version(s) |
---|---|---|---|
.xlsx | ZIP, CFB+ZIP | OpenXml | 2007 and newer |
.xlsb | ZIP, CFB | OpenXml | 2007 and newer |
.xls | CFB | BIFF8 | 97, 2000, XP, 2003 98, 2001, v.X, 2004 (Mac) |
.xls | CFB | BIFF5 | 5.0, 95 |
.xls | - | BIFF4 | 4.0 |
.xls | - | BIFF3 | 3.0 |
.xls | - | BIFF2 | 2.0, 2.2 |
.csv | - | CSV | (All) |
ExcelDataReader
和 ExcelDataReader.DataSet
都是必备的 NuGet 包。此表提供了 ExcelDataReader 的关键功能和属性,方便开发者了解并使用该库进行 Excel 文件读取操作。
方法 | 属性(中文) |
---|---|
Read() | 从当前工作表中读取一行。 |
NextResult() | 将光标移至下一个工作表。 |
ResultsCount | 返回当前工作簿中的工作表数量。 |
Name | 返回当前工作表的名称。 |
CodeName | 返回当前工作表的VBA代码名称标识符。 |
FieldCount | 返回当前工作表中的列数。 |
RowCount | 返回当前工作表中的行数。 |
HeaderFooter | 返回包含页眉和页脚信息的对象,或null 如果没有。 |
MergeCells | 返回当前工作表中合并单元格范围的数组。 |
RowHeight | 返回当前行的视觉高度(以点为单位)。可能为0如果行被隐藏。 |
GetColumnWidth() | 返回列的宽度(以字符单位)。可能为0如果列被隐藏。 |
GetFieldType() | 返回当前行中值的类型。 |
IsDBNull() | 检查当前行中的值是否为null。 |
GetValue() | 从当前行返回一个值作为object ,或null 如果没有值。 |
GetDouble() | 从当前行返回一个值并转换为double 类型。 |
GetInt32() | 从当前行返回一个值并转换为int 类型。 |
GetBoolean() | 从当前行返回一个值并转换为bool 类型。 |
GetDateTime() | 从当前行返回一个值并转换为DateTime 类型。 |
GetString() | 从当前行返回一个值并转换为string 类型。 |
GetNumberFormatString() | 返回当前行中值的格式代码字符串,或null 如果没有值。 |
GetNumberFormatIndex() | 返回当前行中值的数字格式索引。 |
GetCellStyle() | 返回包含当前行中单元格样式信息的对象。 |
以下是如何使用 ExcelDataReader 读取 Excel 文件的基本步骤:
C#using System;
using System.Data;
using System.IO;
using ExcelDataReader;
class Program
{
static void Main()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//注意这个编码注册
// 文件路径
string filePath = @"pgcustomer.xlsx";
// 打开文件流
using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
// 创建 ExcleDataReader
using var reader = ExcelReaderFactory.CreateReader(stream);
// 配置读取选项
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true // 使用第一行作为列名
}
};
// 转换为 DataSet
var result = reader.AsDataSet(conf);
// 遍历所有表
foreach (DataTable table in result.Tables)
{
Console.WriteLine($"Sheet: {table.TableName}");
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write($"{row[column]} ");
}
Console.WriteLine();
}
}
}
}
如果你只想读取特定的工作表,可以按如下方式实现:
JavaScriptvar table = result.Tables["Sheet1"];
C#using System;
using System.Data;
using System.IO;
using System.Linq;
using ExcelDataReader;
class Program
{
static void Main()
{
string filePath = @"path\to\your\excel-file.xlsx";
using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateReader(stream);
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
};
var result = reader.AsDataSet(conf);
var table = result.Tables["Sheet1"];
if (table != null)
{
// 使用 LINQ 进行条件过滤
var filteredRows = table.AsEnumerable()
.Where(row => row.Field<string>("accountpricingcode") == "B002");
foreach (var row in filteredRows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write($"{row[column]} ");
}
Console.WriteLine();
}
}
}
}
.xlsx
, .xls
等常见 Excel 文件格式,但 .xlsm
(包含宏的文件)可能在某些版本中不被完全支持。安装ExcelDataReader.Mapping
C#public class PgCustomer
{
[ExcelColumnName("accountpricingcode")]
public string code { get; set; }
[ExcelColumnName("pg")]
public string pg { get; set; }
[ExcelColumnName("factor")]
public decimal factor { get; set; }
[ExcelColumnName("startdate")]
public DateTime startdate { get; set; }
[ExcelColumnName("enddate")]
public DateTime enddate { get; set; }
}
如果属性名称与excel 列头一样,就不用给ExcelColumnName了。
C#static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//注意这个编码注册
string filePath = @"pgcustomer.xlsx";
using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var importer = new ExcelImporter(stream);
ExcelSheet sheet = importer.ReadSheet();
var pgs = sheet.ReadRows<PgCustomer>().ToList();
foreach (var pg in pgs)
{
Console.Write(pg.code +"\t");
Console.Write(pg.pg + "\t");
Console.Write(pg.factor + "\t");
Console.Write(pg.startdate + "\t");
Console.Write(pg.enddate + "\t");
Console.WriteLine();
}
}
使用 ExcelDataReader,可以轻松实现对 Excel 文件的读取操作,无论是简单的读取还是按条件过滤。通过配置选项,可以灵活地处理不同的文件结构和内容格式。
希望这篇文章对你了解和使用 ExcelDataReader 提供帮助。如果有其他问题,欢迎在评论区提问。
本文作者:rick
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!