c#使用NPOI库创建Excel散点图并使横纵居中显示轴标题和图例删除网格线
以下是使用NPOI库创建Excel散点图并使横纵居中,显示轴标题和图例,删除网格线的示例代码:
using System;
using System.IO;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
class Program
{
static void Main(string[] args)
{
// 创建工作簿
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("ScatterChart");
// 创建数据
IRow row1 = sheet.CreateRow(0);
IRow row2 = sheet.CreateRow(1);
IRow row3 = sheet.CreateRow(2);
IRow row4 = sheet.CreateRow(3);
row1.CreateCell(0).SetCellValue(1);
row1.CreateCell(1).SetCellValue(2);
row2.CreateCell(0).SetCellValue(2);
row2.CreateCell(1).SetCellValue(4);
row3.CreateCell(0).SetCellValue(3);
row3.CreateCell(1).SetCellValue(6);
row4.CreateCell(0).SetCellValue(4);
row4.CreateCell(1).SetCellValue(8);
// 创建图表
XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
XSSFClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, 0, 5, 10, 20);
XSSFChart chart = drawing.CreateChart(anchor);
// 设置图表样式
chart.SetTitleText("Scatter Chart");
chart.SetLegendPosition(LegendPosition.TopRight);
// 创建散点图系列
XSSFScatterChartData data = chart.ChartDataFactory.CreateScatterChartData();
XSSFScatterChartData.Series series = data.AddSerie(sheet.GetRow(0).GetCell(0).Address.ToString(), sheet.GetRow(0).GetCell(1).Address.ToString());
series.SetTitle("Series 1");
chart.Plot(data);
// 设置横纵坐标
IChartAxis xAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
IChartAxis yAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
xAxis.SetTitleText("X Axis");
yAxis.SetTitleText("Y Axis");
chart.SetAxisTitle(AxisPosition.Bottom, "X Axis");
chart.SetAxisTitle(AxisPosition.Left, "Y Axis");
// 设置图表区域和网格线
IChartLegend legend = chart.GetOrCreateLegend();
legend.Position = LegendPosition.TopRight;
chart.SetDisplayBlanksAs(DisplayBlanks.GAP);
chart.SetZoom(1, 1, 0, 0);
chart.SetShowDataLabelsOverMaximum(false);
chart.SetShowHiddenData(false);
chart.SetShowLegend(true);
chart.SetPlotVisibleOnly(false);
chart.SetDisplayTitle(true);
chart.SetDisplayCategories(true);
chart.SetDisplayAxes(true);
chart.SetDisplayUnits(DisplayUnits.NONE);
chart.SetPlotAreaBackgroundColor(0xffffff);
chart.SetFloorFillColor(0xffffff);
chart.SetWallFillColor(0xffffff);
chart.SetLineStyleCompoundLine(Dml.LineStyleValues.Solid, 0, 0, 0, 0, 0, 0);
// 保存文件
FileStream file = new FileStream("ScatterChart.xlsx", FileMode.Create);
workbook.Write(file);
file.Close();
}
}
在上面的示例中,我们首先创建了一个工作簿和一个名为“ScatterChart”的工作表。然后,我们创建了一些数据,并使用NPOI库创建了一个散点图。接下来,我们设置了散点图的样式,包括标题,图例和轴标题。最后,我们设置了图表区域和网格线,并将文件保存到本地磁盘上。
总的来说,使用NPOI库可以很方便地创建和操作Excel文件,包括创建图表和设置样式
原文地址: http://www.cveoy.top/t/topic/hlLV 著作权归作者所有。请勿转载和采集!