背景:网上找了很多excel绘制表格曲线,但是大多方法过于复杂,且不太实用,所以查找了很多资料,最终找到POI可以绘制曲线,废话不多说,直接上图上代码

POI绘制曲线图

	public void CreateGraph(String dataPath, String exportPath, String heapName){
		XSSFWorkbook my_workbook = new XSSFWorkbook();
		XSSFSheet my_worksheet = my_workbook.createSheet(heapName);
		Row row = my_worksheet.createRow(0);
		row.createCell(0).setCellValue("序列");
		row.createCell(1).setCellValue("内存/M");

		ArrayList<Double> mems = ReadLog.Heap(dataPath);
		for (int i = 0; i < mems.size(); i++) {
			row = my_worksheet.createRow(i + 1);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(mems.get(i));
		}

		/*
		 * At the end of this step, we have a worksheet with test data, that we
		 * want to write into a chart
		 */
		/* Create a drawing canvas on the worksheet */
		XSSFDrawing xlsx_drawing = my_worksheet.createDrawingPatriarch();
		// 八个参数,前四个表示图片离起始单元格和结束单元格边缘的位置,
		// 后四个表示起始和结束单元格的位置,如下表示从第2列到第12列,从第1行到第15行,需要注意excel起始位置是0
		XSSFClientAnchor anchor = xlsx_drawing.createAnchor(0, 0, 0, 0, 3, 3, 14, 18);
		/* Create the chart object based on the anchor point */
		XSSFChart my_line_chart = xlsx_drawing.createChart(anchor);
		/*
		 * Define legends for the line chart and set the position of the legend
		 */
		XSSFChartLegend legend = my_line_chart.getOrCreateLegend();
		legend.setPosition(LegendPosition.BOTTOM);
		/* Create data for the chart */
		LineChartData data = my_line_chart.getChartDataFactory().createLineChartData();
		/* Define chart AXIS */
		ChartAxis bottomAxis = my_line_chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
		bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
		bottomAxis.setMajorTickMark(AxisTickMark.NONE);//取消X轴的标刻度
		ValueAxis leftAxis = my_line_chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
		leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
		//添加数据
		ChartDataSource<Number> xs = DataSources.fromNumericCellRange(my_worksheet, new CellRangeAddress(1, mems.size(), 0, 0));
		ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(my_worksheet, new CellRangeAddress(1, mems.size(), 1, 1));
		
		LineChartSeries series = data.addSeries(xs, ys1);
		series.setTitle(heapName);//设置序列名称
		my_line_chart.setTitle("内存曲线");//设置图表标题
		my_line_chart.plot(data, new ChartAxis[] { bottomAxis, leftAxis });
		
		/* Finally define FileOutputStream and write chart information */
		FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(exportPath + ".xlsx");
			my_workbook.write(fileOut);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileOut != null) {
					fileOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

以上就是绘制表格的曲线方法,仅供学习和参考

demo下载链接

相关文章: