网站首页 > 技术文章 正文
ExcelDataReader 是一个轻量级且高效的库,用于读取 .xlsx 和 .xls 文件中的数据。本文将详细介绍如何在 C# 项目中使用 ExcelDataReader 库,并提供多个示例来演示其功能。
前提条件
在开始之前,确保以下环境准备就绪:
- .NET (Core 或 Framework)
- Visual Studio 或其他兼容的 IDE
安装 ExcelDataReader 库
首先,通过 NuGet 包管理器安装 ExcelDataReader 库。您可以在 NuGet 包管理器控制台中运行下面的命令:
Install-Package ExcelDataReader
此外,还需要安装一个支持读取方式的包:
Install-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 和 ExcelDataReader.DataSet 都是必备的 NuGet 包。
- 确保在不同的 .NET 版本下正确注册编码提供程序,例如对 .NET Framework 需要特定的编码注册步骤。
此表提供了 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 文件的基本步骤:
- 打开文件流
- 使用 ExcelReaderFactory 创建 IExcelDataReader
- 可选:将数据转换为 DataSet
- 处理数据
- 关闭数据读取器和文件流
代码示例
读取 Excel 文件并输出内容
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(#34;Sheet: {table.TableName}");
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write(#34;{row[column]} ");
}
Console.WriteLine();
}
}
}
}
读取 Excel 文件中的特定工作表
如果你只想读取特定的工作表,可以按如下方式实现:
var table = result.Tables["Sheet1"];
按条件过滤内容
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(#34;{row[column]} ");
}
Console.WriteLine();
}
}
}
}
注意事项
- 文件格式支持:ExcelDataReader 支持 .xlsx, .xls 等常见 Excel 文件格式,但 .xlsm (包含宏的文件)可能在某些版本中不被完全支持。
- 文件流:务必正确管理文件流的打开和关闭,以防止资源泄漏。
- 日期格式:确保 Excel 文件中的日期格式一致,否则在解析时可能出现异常。
Maper
安装ExcelDataReader.Mapping
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了。
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 提供帮助。如果有其他问题,欢迎在评论区提问。
如果你正在从事上位机、自动化、机器视觉、物联网(IOT)项目或数字化转型方面的工作,欢迎加入我的圈子!在这里,我们不仅可以轻松畅聊最新技术动态和行业趋势,还能够在技术问题上互相帮助和支持。我会尽量利用我的知识和经验来帮助你解决问题,当然也期待从大家的专业见解中学习和成长。无论你是新手还是老鸟,期待与志同道合的朋友交流心得,一起进步!
猜你喜欢
- 2025-04-30 基本语法 - C#入门教程(c#基础语法汇总pdf)
- 2025-04-30 C# OpenCV机器视觉:缺陷检测(opencv缺陷检测案例)
- 2025-04-30 C#与TypeScript语法深度对比(c#typeof作用)
- 2025-04-30 .NET10:C#14的一些新功能(c# 10.0)
- 2025-04-30 39.C# 接口(c#接口是什么)
- 2025-04-30 C# 中的Async 和 Await 的用法详解
- 2025-04-30 C#之类型转换(c#类型转换有哪几种)
- 2025-04-30 设计模式(C#) - 装饰器模式实现详解
- 2025-04-30 C#中的Channel(c#中的类由哪三个部分组成)
- 2025-04-30 C# 管道模式:构建灵活、可扩展的处理流程
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- sqlset (59)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)