Java调用Excel绘制折线图(附Apache POI代码示例)
使用Java在Excel中绘制折线图:Apache POI库实战教程
想要在Java应用程序中调用Excel并直接绘制折线图? Apache POI库为你提供完美解决方案!本文将提供一个简单易懂的示例代码,演示如何使用Java调用Excel并在Excel文件中绘制折线图,并附带详细的代码解释和Maven依赖配置。
1. 添加Apache POI库依赖
在开始编写代码之前,你需要将Apache POI库添加到你的Java项目中。 你可以使用Maven或Gradle等构建工具来管理依赖。以下是Maven的依赖配置示例,你需要将其添加到项目的pom.xml文件中:xml
2. Java代码示例
添加完依赖后,你就可以开始编写Java代码了。 下面是一个完整的示例代码,演示了如何使用Java调用Excel并在Excel文件中绘制折线图:javaimport org.apache.poi.ss.usermodel.;import org.apache.poi.xssf.usermodel.;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.chart.;import org.apache.poi.chart.data.;
import java.io.FileOutputStream;import java.io.IOException;
public class ExcelLineChartExample { public static void main(String[] args) throws IOException { // 1. 创建Excel工作簿 Workbook workbook = new XSSFWorkbook();
// 2. 创建Excel工作表 Sheet sheet = workbook.createSheet('折线图示例');
// 3. 创建数据行 Row row1 = sheet.createRow(0); row1.createCell(0).setCellValue('X'); row1.createCell(1).setCellValue('Y');
Row row2 = sheet.createRow(1); row2.createCell(0).setCellValue(1); row2.createCell(1).setCellValue(10);
Row row3 = sheet.createRow(2); row3.createCell(0).setCellValue(2); row3.createCell(1).setCellValue(20);
Row row4 = sheet.createRow(3); row4.createCell(0).setCellValue(3); row4.createCell(1).setCellValue(30);
// 4. 创建折线图 Drawing<?> drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 0, 10, 10); Chart chart = drawing.createChart(anchor); ChartLegend legend = chart.getOrCreateLegend(); legend.setPosition(LegendPosition.TOP_RIGHT);
LineChartData data = chart.getChartDataFactory().createLineChartData();
// 5. 创建数据系列 ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 3, 0, 0)); ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 3, 1, 1)); LineChartSeries series = data.addSeries(xs, ys); series.setTitle('数据系列');
// 6. 设置图表标题和轴 ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); chart.plot(data, bottomAxis, leftAxis);
// 7. 保存Excel文件 FileOutputStream fileOut = new FileOutputStream('output.xlsx'); workbook.write(fileOut); fileOut.close();
// 8. 关闭工作簿 workbook.close();
System.out.println('折线图已生成并保存到output.xlsx文件。');
原文地址: https://www.cveoy.top/t/topic/f3iu 著作权归作者所有。请勿转载和采集!