NPOI库是一个用于.NET平台的开源库,可以用于读写Microsoft Office格式的文件,包括Excel、Word和PowerPoint等。以下是使用NPOI库创建Excel图表的步骤:

  1. 引入NPOI库

在Visual Studio中,右键项目,选择“管理NuGet程序包”,搜索并安装“NPOI”。

  1. 创建Excel文件

使用NPOI库创建Excel文件的代码如下:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

// 创建Excel文件
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
  1. 填充数据

向Excel文件中填充数据的代码如下:

// 填充数据
IRow row1 = sheet.CreateRow(0);
row1.CreateCell(0).SetCellValue("A");
row1.CreateCell(1).SetCellValue("B");
row1.CreateCell(2).SetCellValue("C");

IRow row2 = sheet.CreateRow(1);
row2.CreateCell(0).SetCellValue(1);
row2.CreateCell(1).SetCellValue(2);
row2.CreateCell(2).SetCellValue(3);

IRow row3 = sheet.CreateRow(2);
row3.CreateCell(0).SetCellValue(4);
row3.CreateCell(1).SetCellValue(5);
row3.CreateCell(2).SetCellValue(6);
  1. 创建图表

使用NPOI库创建Excel图表的代码如下:

// 创建图表
ISheet sheet2 = workbook.CreateSheet("Sheet2");
IDrawing drawing = sheet2.CreateDrawingPatriarch();
IClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, 5, 1, 15, 20);
IChart chart = drawing.CreateChart(anchor);

// 设置图表类型
chart.ChartType = NPOI.SS.UserModel.Chart.ChartType.Line;

// 设置数据源
IChartDataSource<string> xs = DataSources.FromStringCellRange(sheet.GetRow(0).GetCell(0), sheet.GetRow(2).GetCell(0));
IChartDataSource<double> ys1 = DataSources.FromNumericCellRange(sheet.GetRow(0).GetCell(1), sheet.GetRow(2).GetCell(1));
IChartDataSource<double> ys2 = DataSources.FromNumericCellRange(sheet.GetRow(0).GetCell(2), sheet.GetRow(2).GetCell(2));

// 添加数据系列
IChartSeries series1 = chart.AddSeries(xs, ys1);
series1.SetTitle("Series 1");

IChartSeries series2 = chart.AddSeries(xs, ys2);
series2.SetTitle("Series 2");

// 输出Excel文件
using (FileStream stream = new FileStream("output.xls", FileMode.Create))
{
    workbook.Write(stream);
}

以上代码中,我们创建了一个Line类型的图表,设置了数据源和数据系列,并输出了Excel文件。可以根据需要修改代码中的图表类型、数据系列等参数

c#使用NPOI库创建Excel图表

原文地址: http://www.cveoy.top/t/topic/hlI0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录