使用Apache POI绘制折线图

最近因为项目需要,学习了一下使用Apache POI绘制Excel折线图,话不多说,直接上代码。

		String filePath = "DTD.xlsx";
		FileInputStream inPut = new FileInputStream(filePath);
		
		Workbook workBook = new XSSFWorkbook(inPut);
		FileOutputStream outPut = new FileOutputStream(filePath);
		
		Sheet sheet = workBook.getSheetAt(0);
		
		//创建绘图区域
		Drawing drawing = sheet.createDrawingPatriarch();
		ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 2, 16, 20);
		 
		Chart chart = drawing.createChart(anchor);
		
		//创建图形注释的位置
		ChartLegend legend = chart.getOrCreateLegend();
		legend.setPosition(LegendPosition.TOP);
		
		//创建绘图的类型   LineCahrtData 折线图
		LineChartData chartData = chart.getChartDataFactory().createLineChartData();
		
		//设置横坐标
		ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
		bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
		//设置纵坐标
		ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
		leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
		
		//从Excel中获取数据
		ChartDataSource xAxis = DataSources.fromStringCellRange(sheet, new CellRangeAddress(23, 23, 2, 25));
		ChartDataSource dataAxis = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(24, 24, 2, 25));
		ChartDataSource dataAxis1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(26, 26, 2, 25));
		
		//将获取到的数据填充到折线图
		LineChartSeries chartSeries = chartData.addSeries(xAxis, dataAxis);
		LineChartSeries chartSeries1 = chartData.addSeries(xAxis, dataAxis1);
		
		//给每条这项创建名字
		chartSeries.setTitle(sheet.getRow(24).getCell(1).getStringCellValue());
		chartSeries1.setTitle(sheet.getRow(26).getCell(1).getStringCellValue());
		
		//开始绘制折线图
		chart.plot(chartData, bottomAxis, leftAxis);
		
		workBook.write(outPut);
		outPut.close();


效果图如下:

使用Apache POI绘制折线图_第1张图片

这个折线图还不完美,还再进一步研究“带数据标记的折线图”,文中有错误和不足的地方,希望大家可以指出来。同时,也希望各位要是知道怎么用Apache POI绘制“带数据标记的折线图”,可以教教我,谢谢。

你可能感兴趣的:(Java)