NPOI 开源项目教程
项目介绍
NPOI 是一个 .NET 版本的 Apache POI 项目。Apache POI 是一个开源项目,可以帮助用户读写 xls、doc、ppt 文件。NPOI 继承了这一功能,使得在 .NET 环境下可以轻松读写 Office 2003/2007 文件。NPOI 完全免费,覆盖了 Excel 的大多数功能,包括单元格样式、数据格式、公式等,并支持 xls、xlsx、docx 等格式。
项目快速启动
安装 NPOI
首先,通过 NuGet 安装 NPOI 包:
dotnet add package NPOI --version 2.7.1
创建一个新的 Excel 文件
以下是一个简单的示例,展示如何使用 NPOI 创建一个新的 Excel 文件并添加一些数据:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
class Program
{
static void Main()
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet1 = workbook.CreateSheet("Sheet1");
IRow row1 = sheet1.CreateRow(0);
ICell cellA1 = row1.CreateCell(0);
cellA1.SetCellValue("Hello");
ICell cellB1 = row1.CreateCell(1);
cellB1.SetCellValue("World");
using (FileStream fs = new FileStream("Example.xlsx", FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
}
应用案例和最佳实践
生成 Excel 报告
NPOI 可以用于生成复杂的 Excel 报告,无需安装 Microsoft Office。以下是一个生成包含图表的 Excel 报告的示例:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.IO;
class Program
{
static void Main()
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Report");
// 添加数据
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Month");
headerRow.CreateCell(1).SetCellValue("Sales");
IRow dataRow = sheet.CreateRow(1);
dataRow.CreateCell(0).SetCellValue("January");
dataRow.CreateCell(1).SetCellValue(1000);
// 添加图表
IDrawing drawing = sheet.CreateDrawingPatriarch();
IClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, 0, 2, 10, 15);
IChart chart = drawing.CreateChart(anchor);
IChartLegend legend = chart.GetOrCreateLegend();
legend.SetPosition(LegendPosition.Right);
ILineChartData<string, double> lineChartData = chart.ChartDataFactory.CreateLineChartData<string, double>();
IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
IChartAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
IChartDataSource<string> categories = DataSources.FromStringCellRange(sheet, new CellRangeAddress(1, 1, 0, 0));
IChartDataSource<double> values = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(1, 1, 1, 1));
lineChartData.AddSeries(categories, values);
chart.Plot(lineChartData, bottomAxis, leftAxis);
using (FileStream fs = new FileStream("Report.xlsx", FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
}
典型生态项目
NPOI 作为一个强大的 .NET 库,广泛应用于各种需要处理 Office 文件的项目中。以下是一些典型的生态项目:
- 数据报表生成:使用