java修改excel图表数据源,导出excel图表文件 您所在的位置:网站首页 excel表格图标数据源 java修改excel图表数据源,导出excel图表文件

java修改excel图表数据源,导出excel图表文件

2024-07-11 11:19| 来源: 网络整理| 查看: 265

1.首先需要引进poi相关依赖,需要注意的是,如果没有ooxml-schemas,代码是会报错的

org.apache.poi ooxml-schemas 1.0

2.java导出带柱状图或饼状图的excel其实有两种方式,一种是直接创建新的excel文件,在该文件中写入柱状图或其他的图,并写入数据源,这种方式相对来说较复杂,因为需要设置很多图的样式;第二种是直接读取本地的模板excel文件,把文件中已经创建好的的图表赋值我们从后台查询的数据,这种方式比较简单,很多样式都可以在模板中设置好,我们直接获取excel文件中的各个图,再分别指定数据源即可

String path = "模板存放全路径"; File excel = new File(path); //写入数据到excel文件中,只写第一列和第二列,表头除外 FileInputStream is = new FileInputStream(excel); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is); //获取创建工作簿的第一页 XSSFSheet sheet = xssfWorkbook.getSheetAt(0); //自动计算 sheet.setForceFormulaRecalculation(true); //给指定的sheet命名 xssfWorkbook.setSheetName(0, "图表统计"); //存储当前表格的样式 XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle(); //遍历列,填充数据 for (int i = 0; i < lstStatistic.size(); i++) { Row row = sheet.createRow(i+1); row.createCell(0).setCellValue(lstStatistic.get(i).getString(mapParams.get("onStatisticField").toString()));//key row.createCell(1).setCellValue(lstStatistic.get(i).getDoubleValue(mapParams.get("outStatisticFieldName").toString()));//value } //遍历图表,设置图表的选值范围---仅支持xlsx格式的excel XSSFDrawing drawingPatriarch = sheet.getDrawingPatriarch(); //拿到图形 List charts = drawingPatriarch.getCharts(); XSSFChart chart = null; CTChart ctChart = null; CTPlotArea plotArea = null; /*-----------------柱状图-------------------*/ chart = charts.get(0); ctChart = chart.getCTChart(); plotArea = ctChart.getPlotArea(); // 获取图表的系列 CTBarSer serBar = plotArea.getBarChartArray(0).getSerArray(0); // serBar.getTx().getStrRef().setF("柱状图"); // 指定数据区域 serBar.getCat().getNumRef().setF("图表统计!$A$2:$A$"+(lstStatistic.size()+1)); serBar.getVal().getNumRef().setF("图表统计!$B$2:$B$"+(lstStatistic.size()+1)); /*------------------饼状图-----------------*/ chart = charts.get(1); ctChart = chart.getCTChart(); plotArea = ctChart.getPlotArea(); CTPieSer serPipe = plotArea.getPieChartArray(0).getSerArray(0); serPipe.getCat().getNumRef().setF("图表统计!$A$2:$A$"+(lstStatistic.size()+1)); serPipe.getVal().getNumRef().setF("图表统计!$B$2:$B$"+(lstStatistic.size()+1)); //写出 FileOutputStream os = new FileOutputStream(excel); xssfWorkbook.write(os); xssfWorkbook.close(); //TODO 流的处理 is.close(); os.flush(); os.close();

这里注意一点就是,只支持xlsx格式的excel文件

3.本地模板文件截图如下



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有