c#使用NPOI 256库创建Excel散点图
以下是使用NPOI 2.5.6库创建Excel散点图的示例代码:
using System;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.Chart;
using NPOI.Chart.Util;
public class ScatterChartExample
{
public static void Main(string[] args)
{
// Create workbook
XSSFWorkbook workbook = new XSSFWorkbook();
// Create worksheet
ISheet sheet = workbook.CreateSheet("Scatter Chart");
// Set data for X and Y axis
IRow row1 = sheet.CreateRow(0);
row1.CreateCell(0).SetCellValue("X");
row1.CreateCell(1).SetCellValue("Y");
for (int i = 1; i <= 10; i++)
{
IRow row = sheet.CreateRow(i);
row.CreateCell(0).SetCellValue(i);
row.CreateCell(1).SetCellValue(i * i);
}
// Create chart
XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
XSSFClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, 4, 0, 15, 15);
IChart chart = drawing.CreateChart(anchor);
// Set chart type to scatter chart
chart.ChartType = NPOI.SS.UserModel.Chart.ChartType.Scatter;
// Add data to chart
IChartDataSource<Number> x = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(1, 10, 0, 0));
IChartDataSource<Number> y = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(1, 10, 1, 1));
IScatterChartData<Number, Number> data = chart.ChartDataFactory.CreateScatterChartData<Number, Number>(x, y);
chart.ChartData = data;
// Set chart title
IChartTitle chartTitle = chart.Title;
chartTitle.SetText("Scatter Chart");
// Set X axis title
IAxis xAxis = chart.GetChartAxisFactory().CreateCategoryAxis(AxisPosition.Bottom);
xAxis.Title.SetText("X");
// Set Y axis title
IAxis yAxis = chart.GetChartAxisFactory().CreateValueAxis(AxisPosition.Left);
yAxis.Title.SetText("Y");
// Save workbook
FileStream file = new FileStream("ScatterChartExample.xlsx", FileMode.Create);
workbook.Write(file);
file.Close();
}
}
这个示例程序创建一个包含X和Y轴数据的Excel工作表,并使用NPOI 2.5.6库创建一个散点图。程序将数据添加到图表中,设置图表标题,X轴标题和Y轴标题,并将工作簿保存为Excel文件
原文地址: http://www.cveoy.top/t/topic/hlNb 著作权归作者所有。请勿转载和采集!