package 折线图;import orgapachepoissusermodelClientAnchor;import orgapachepoissusermodelDrawing;import orgapachepoissusermodelRow;import orgapachepoissusermodelcharts;import orgapachepoissutilCellRangeAd
当使用Apache POI创建Excel折线图时,有些方法已经被禁用,可以进行优化。以下是优化的代码示例:
package 折线图;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelChartExample {
public static void main(String[] args) {
try {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("折线图");
// 创建数据行和列
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("X");
row.createCell(1).setCellValue("Y");
// 填充数据
for (int i = 1; i <= 10; i++) {
row = sheet.createRow(i);
row.createCell(0).setCellValue(i);
row.createCell(1).setCellValue(i * i);
}
// 创建折线图
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 10, 20);
Chart chart = drawing.createChart(anchor);
chart.setTitleText("数据折线图");
chart.setTitleOverlay(false);
// 设置图例位置
chart.getOrAddLegend().setPosition(LegendPosition.BOTTOM);
// 创建数据系列
LineChartData data = chart.getChartDataFactory().createLineChartData();
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 创建数据源
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 0, 0));
ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 1, 1));
// 添加数据系列
LineChartSeries series = data.addSeries(xs, ys);
series.setTitle("数据折线图");
// 绘制图表
chart.plot(data, bottomAxis, leftAxis);
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("折线图已创建并保存到Excel文件中。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在优化后的代码中,主要进行了以下更改:
- 使用
Workbook接口的实现类XSSFWorkbook创建工作簿。 - 使用
Sheet接口的createSheet方法创建工作表。 - 使用
chart.setTitleText方法设置图表标题。 - 使用
chart.setTitleOverlay方法设置图表标题是否覆盖图表。 - 使用
chart.getOrAddLegend方法获取或添加图例,并使用setPosition方法设置图例位置。 - 创建折线图数据时,使用
chart.getChartDataFactory()方法创建LineChartData对象。 - 创建数据系列时,使用
chart.getChartAxisFactory()方法创建横轴和纵轴对象。 - 使用
chart.plot方法绘制图表。
通过这些优化,可以确保代码在使用最新的POI库时仍然有效,并且更加简洁和易读
原文地址: http://www.cveoy.top/t/topic/hAHt 著作权归作者所有。请勿转载和采集!