java使用poi操作world生成饼图,柱状图,折线图,组合图:二

  • 上文和问题链接
  • 直接上代码
    • maven
    • 测试类:单图表(入口)
    • 测试类:组合图表(入口)
    • 工具类:组合数据类
    • 工具类:枚举解析图表类
    • 工具类:图片写入

上文和问题链接

上文链接:java使用poi操作world生成饼图,柱状图,折线图,组合图:一
问题链接:java poi 操作word遇到的问题

直接上代码

maven

<!--#############world操作所需依赖###########--><dependency><groupId>xml-apis</groupId><artifactId>xml-apis</artifactId><version>1.4.01</version></dependency><!-- https://mvnrepository.com/artifact/commons-io/commons-io --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.10.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.4</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.13</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.19</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version></dependency>

测试类:单图表(入口)

可能遇到读取不到指定的图表----------更换第二个下标
chartModel.setSingleChart(charts,2,0,ChartsEnum.COLUMN);

import lombok.SneakyThrows;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFChart;import java.io.*;
import java.util.*;/*** @author BM_hyjw* word图表写入数据实现测试*/
public class Single {public static void main(String[] args) throws IOException, InvalidFormatException {//获取word模板InputStream docis = new FileInputStream("C:\\Users\\16630\\Desktop\\htmlToLongImage\\haha.docx");//转成wordCustomXWPFDocument doc = new CustomXWPFDocument(docis);//获取word中所有图表对象List<XWPFChart> charts = doc.getCharts();//数据源ChartModel chartModel = new ChartModel();//标题List<String> titleList = new ArrayList<String>();titleList.add("type");titleList.add("number");chartModel.setTitleList(titleList);//字段名List<String> numberList = new ArrayList<String>();numberList.add("value1");numberList.add("value2");chartModel.setNumberList(numberList);//记录某本书销售多少册List<Map<String, String>> sourceModelList = new ArrayList<>();Map<String, String> publicEm = new HashMap<>();publicEm.put("value1", "设计模式之禅");publicEm.put("value2", "555");Map<String, String> publicEm1 = new HashMap<>();publicEm1.put("value1", "effective java");publicEm1.put("value2", "453");Map<String, String> publicEm2 = new HashMap<>();publicEm2.put("value1", "红楼梦");publicEm2.put("value2", "982");Map<String, String> publicEm3 = new HashMap<>();publicEm3.put("value1", "水浒传");publicEm3.put("value2", "759");sourceModelList.add(publicEm);sourceModelList.add(publicEm1);sourceModelList.add(publicEm2);sourceModelList.add(publicEm3);chartModel.setSourceModelList(sourceModelList);//得到模板中第 N 个位置的图表可绘制区域中 条形图chartModel.setSingleChart(charts,2,0,ChartsEnum.COLUMN);chartModel.executeFillModel("sheet1");//得到模板中第 N 个位置的图表可绘制区域中 饼状图chartModel.setSingleChart(charts,3,0,ChartsEnum.PIE);chartModel.executeFillModel("sheet1");//得到模板中第 N 个位置的图表可绘制区域中 折线图chartModel.setSingleChart(charts,4,0,ChartsEnum.LINE_CHART);chartModel.executeFillModel("sheet1");try (FileOutputStream fos = new FileOutputStream("test.docx")) {doc.write(fos);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

测试类:组合图表(入口)

第一个图表:
对应Map数据源中第一个key做X轴 第二个key做Y轴
第二个图表:
对应Map数据源中第一个key做X轴 第三个key做Y轴

import lombok.SneakyThrows;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFChart;import java.io.*;
import java.util.*;/*** @author BM_hyjw* word图表写入数据实现测试*/
public class Combination{@SneakyThrowspublic static void main(String[] args) {//获取word模板InputStream docis = new FileInputStream("C:\\Users\\16630\\Desktop\\htmlToLongImage\\haha.docx");//转成wordCustomXWPFDocument doc = new CustomXWPFDocument(docis);//获取word中所有图表对象List<XWPFChart> charts = doc.getCharts();//数据源ChartModel chartModel = new ChartModel();//标题List<String> titleList = new ArrayList<String>();titleList.add("type");titleList.add("number");titleList.add("max");chartModel.setTitleList(titleList);//字段名List<String> numberList = new ArrayList<String>();numberList.add("value1");numberList.add("value2");numberList.add("value3");chartModel.setNumberList(numberList);//记录某本书销售多少册List<Map<String, String>> sourceModelList = new ArrayList<>();Map<String, String> publicEm = new HashMap<>();publicEm.put("value1", "设计模式之禅");publicEm.put("value2", "555");publicEm.put("value3", "0");Map<String, String> publicEm1 = new HashMap<>();publicEm1.put("value1", "effective java");publicEm1.put("value2", "453");publicEm1.put("value3", "0");Map<String, String> publicEm2 = new HashMap<>();publicEm2.put("value1", "红楼梦");publicEm2.put("value2", "982");publicEm2.put("value3", "982");Map<String, String> publicEm3 = new HashMap<>();publicEm3.put("value1", "水浒传");publicEm3.put("value2", "759");publicEm3.put("value3", "759");sourceModelList.add(publicEm);sourceModelList.add(publicEm1);sourceModelList.add(publicEm2);sourceModelList.add(publicEm3);chartModel.setSourceModelList(sourceModelList);//得到模板中第  N 个位置的图表可绘制区域中 折线图 和 柱状图 的 组合图chartModel.setComBiChart(charts,0,0,Arrays.asList(ChartsEnum.LINE_CHART,ChartsEnum.COLUMN));chartModel.executeFillModel("sheet1");//得到模板中第  N 个位置的图表可绘制区域中 折线图 和 散点 的 组合图chartModel.setComBiChart(charts,1,0,Arrays.asList(ChartsEnum.LINE_CHART,ChartsEnum.SCATTER));chartModel.executeFillModel("sheet1");try (FileOutputStream fos = new FileOutputStream("test.docx")) {doc.write(fos);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

工具类:组合数据类

package com.wyz.world.utils;import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.xmlbeans.XmlObject;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;/*** @author BM_hyjw* 图表要填充的数据格式*/
@Slf4j
@Getter
@ToString
public class ChartModel {/*** 标记 用来记录当前是否是单元素的图表*/private Boolean isSingle = true;/*** 内置表格页名*/private String sheetName;/*** 图表*/private XWPFChart xwpfChart;/*** 具体图*/private List<XmlObject> xmlObjectList = new ArrayList<>();/*** 绘制区域图*/private CTChart ctChart;/*** 标题*/private List<String> titleList;/*** 数据源对应的key*/private List<String> numberList;/*** 填充的数据源*/private List<Map<String, String>> sourceModelList;/*** 目标数据*/private List<ChartsEnum> chartsEnumList;/*** 赋值 替换目标* @param numberList*/public void setNumberList(List<String> numberList){this.numberList = numberList;}/*** 赋值 数据源* @param sourceModelList*/public void setSourceModelList(List<Map<String, String>> sourceModelList){this.sourceModelList = sourceModelList;}/*** 赋值 标题* @param titleList*/public void setTitleList(List<String> titleList){this.titleList = titleList;}/*** 单个赋值 图表* @param charts 所有可绘制区域* @param chartSeat 要操作的图表中可绘制区域位置* @param xmlObjSeat 图表在可绘制区域中的位置* @param chartsEnum 目标的表格类型*/public void setSingleChart(List<XWPFChart> charts,int chartSeat,int xmlObjSeat,ChartsEnum chartsEnum){List<ChartsEnum> chartsEnumList = Arrays.asList(chartsEnum);/*** 封装基础数据*/this.packageBasic(charts, chartSeat,chartsEnumList);/*** 获得目标图表*/XmlObject targetChart = chartsEnum.getTargetChart(chartSeat, this.ctChart, xmlObjSeat);this.xmlObjectList = Arrays.asList(targetChart);//当前是单元素this.isSingle = true;}/*** 组合赋值 图表* @param charts 所有可绘制区域* @param chartSeat 要操作的图表中可绘制区域位置* @param xmlObjSeat 图表在可绘制区域中的位置* @param chartsEnumList 目标的表格类型*/public void setComBiChart(List<XWPFChart> charts,int chartSeat,int xmlObjSeat,List<ChartsEnum> chartsEnumList){/*** 封装基础数据*/this.packageBasic(charts, chartSeat,chartsEnumList);/*** 获得目标图表*/this.xmlObjectList.clear();chartsEnumList.stream().forEach(x->{XmlObject targetChart = x.getTargetChart(chartSeat,this.ctChart, xmlObjSeat);this.xmlObjectList.add(targetChart);});//当前不是单元素this.isSingle = false;}/*** 封装部分基础数据* @param charts* @param chartSeat* @param chartsEnumList*/private void packageBasic(List<XWPFChart> charts, int chartSeat,List<ChartsEnum> chartsEnumList) {if(CollectionUtils.isEmpty(charts)){throw new RuntimeException("模板中图表元素为null; !!!ctChart:null");}if(CollectionUtils.isEmpty(chartsEnumList)){throw new RuntimeException("图表目标为null;!!!chartsEnum:null");}/*** 目标*/this.chartsEnumList = chartsEnumList;/*** 第N个位置图表*/this.xwpfChart = charts.get(chartSeat);/*** 第N个位置可绘制区域的图表*/this.ctChart = this.xwpfChart.getCTChart();}/*** 执行模板数据源填充* @param sheetName 展示数据excel页名字*/public void executeFillModel(String sheetName) throws IOException, InvalidFormatException {this.sheetName = sheetName;//异常校验String s = this.isSingle ? this.abnormalCheckSingle() : this.abnormalCheckComBi();//执行填充数据ChartsEnum.refreshExcel(this);for (int i = 0; i < chartsEnumList.size(); i++) {ChartsEnum chartsEnum = chartsEnumList.get(i);chartsEnum.fillModel(this,this.getXmlObjectList().get(i),i);}}/*** 异常校验*/private String abnormalCheckSingle() {if(CollectionUtils.isEmpty(this.numberList)){throw new RuntimeException("数据源比对为null; !!!numberList:null");}if(CollectionUtils.isEmpty(this.titleList)){throw new RuntimeException("标题为null; !!!titleList:null");}if(CollectionUtils.isEmpty(this.sourceModelList)){throw new RuntimeException("数据源为null; !!!sourceModelList:null");}if(Objects.isNull(this.xwpfChart)){throw new RuntimeException("模板中图表元素为null; !!!xwpfChart:null");}if(CollectionUtils.isEmpty(this.xmlObjectList)){throw new RuntimeException("模板中具体图表为null;!!!xmlObjectList:null");}if(CollectionUtils.isEmpty(this.chartsEnumList)){throw new RuntimeException("图表目标为null;!!!chartsEnum:null");}if(Objects.isNull(this.ctChart)){throw new RuntimeException("图表绘制区域为null;!!!chartsEnum:null");}if(StringUtils.isEmpty(this.sheetName)){throw new RuntimeException("内置excel页名为null;!!!sheetName:null");}return null;}/*** 异常校验*/private String abnormalCheckComBi() {this.abnormalCheckSingle();if (this.xmlObjectList.size() < 2) {throw new RuntimeException("组合图中【图表】元素不足两个; !!!xmlObjectList.size !> 2");}if (this.sourceModelList.stream().filter(x->{return x.keySet().size() >= 3;}).collect(Collectors.toList()).size() < 0) {throw new RuntimeException("组合图中【数据源】元素不足两个; !!!sourceModelList.map.keySet.size !>= 3");}if (this.numberList.size() < 3) {throw new RuntimeException("组合图中【数据源对应的key】元素不足两个; !!!numberList.size !>= 3");}return null;}
}

工具类:枚举解析图表类

package com.wyz.world.utils;import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.values.XmlComplexContentImpl;
import org.openxmlformats.schemas.drawingml.x2006.chart.*;
import org.openxmlformats.schemas.drawingml.x2006.chart.impl.CTBarChartImpl;
import org.openxmlformats.schemas.drawingml.x2006.chart.impl.CTLineChartImpl;
import org.openxmlformats.schemas.drawingml.x2006.chart.impl.CTPieChartImpl;
import org.openxmlformats.schemas.drawingml.x2006.chart.impl.CTScatterChartImpl;import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;/*** @author BM_hyjw* 解析world 中图表*/
@Slf4j
@Getter
public enum ChartsEnum {/*** 饼图*/PIE(CTPieChart.class, CTPieChartImpl.class){/*** 填充模板数据* @param chartModel 图表和数据源* @param xmlObject 当前元素* @param bias 偏向值*/@Overridepublic void fillModel(ChartModel chartModel,XmlObject xmlObject,int bias) {if (!this.chartImplClazz.getName().equals(xmlObject.getClass().getName())) {//当前循环中图表操作不属于当前枚举ChartsEnum.getEnumByChartImplClazz(((XmlComplexContentImpl)xmlObject).getClass()).fillModel(chartModel, xmlObject, bias);return;}CTPieChart pieChart = (CTPieChart)xmlObject;List<CTPieSer> serList = pieChart.getSerList();//更新数据区域for (int i = 0; i < serList.size(); i++) {//数据填充//CTPieSer ser = pieChart.getSerArray(i);CTAxDataSource cat = ser.getCat();CTNumDataSource val = ser.getVal();this.dataAnalysisFill(chartModel,i,bias,cat,val);}}/*** 得到目标位置的图表* @param ctChart 可绘制区域图表* @param xmlObjSeat 目标图标位置位置* @return*/@Overridepublic XmlObject getTargetChart(int chartSeat, CTChart ctChart, int xmlObjSeat) {try {CTPieChart pieChart = ctChart.getPlotArea().getPieChartArray(xmlObjSeat);return pieChart;}catch (Exception e){throw new RuntimeException("当前位置【" + chartSeat + "】不存在【饼图】!!!");}}},/*** 柱图*/COLUMN(CTBarChart.class, CTBarChartImpl.class) {/*** 填充模板数据* @param chartModel 图表和数据源* @param bias 偏向值*/@Overridepublic void fillModel(ChartModel chartModel,XmlObject xmlObject,int bias) {if (!this.chartImplClazz.getName().equals(xmlObject.getClass().getName())) {//当前循环中图表操作不属于当前枚举ChartsEnum.getEnumByChartImplClazz(((XmlComplexContentImpl)xmlObject).getClass()).fillModel(chartModel, xmlObject, bias);return;}CTBarChart chart = (CTBarChart)xmlObject;List<CTBarSer> serList = chart.getSerList();//更新数据区域for (int i = 0; i < serList.size(); i++) {//数据填充//CTBarSer ser = chart.getSerArray(i);CTAxDataSource cat = ser.getCat();CTNumDataSource val = ser.getVal();this.dataAnalysisFill(chartModel,i,bias,cat,val);}}/*** 得到目标位置的图表* @param ctChart 可绘制区域图表* @param xmlObjSeat 目标图标位置位置* @return*/@Overridepublic XmlObject getTargetChart(int chartSeat, CTChart ctChart, int xmlObjSeat) {try {CTBarChart barChart = ctChart.getPlotArea().getBarChartArray(xmlObjSeat);return barChart;}catch (Exception e){throw new RuntimeException("当前位置【" + chartSeat + "】不存在【柱状图】!!!");}}},/*** 折线图*/LINE_CHART(CTLineChart.class, CTLineChartImpl.class){/*** 填充模板数据* @param chartModel 图表和数据源* @param xmlObject 当前元素* @param bias 偏向值*/@Overridepublic void fillModel(ChartModel chartModel,XmlObject xmlObject,int bias) {if (!this.chartImplClazz.getName().equals(xmlObject.getClass().getName())) {//当前循环中图表操作不属于当前枚举ChartsEnum.getEnumByChartImplClazz(((XmlComplexContentImpl)xmlObject).getClass()).fillModel(chartModel, xmlObject, bias);return;}CTLineChart chart = (CTLineChart)xmlObject;List<CTLineSer> serList = chart.getSerList();//更新数据区域for (int i = 0; i < serList.size(); i++) {//数据填充//CTLineSer ser = chart.getSerArray(i);CTAxDataSource cat = ser.getCat();CTNumDataSource val = ser.getVal();this.dataAnalysisFill(chartModel,i,bias,cat,val);}}/*** 得到目标位置的图表* @param ctChart 可绘制区域图表* @param xmlObjSeat 目标图标位置位置* @return*/@Overridepublic XmlObject getTargetChart(int chartSeat, CTChart ctChart, int xmlObjSeat) {try {CTLineChart lineChart = ctChart.getPlotArea().getLineChartArray(xmlObjSeat);return lineChart;}catch (Exception e){throw new RuntimeException("当前位置【" + chartSeat + "】不存在【折线图】!!!");}}},/*** 散点图*/SCATTER(CTScatterChart.class, CTScatterChartImpl.class){/*** 填充模板数据* @param chartModel 图表和数据源* @param xmlObject 当前元素* @param bias 偏向值*/@Overridepublic void fillModel(ChartModel chartModel,XmlObject xmlObject,int bias) {if (!this.chartImplClazz.getName().equals(xmlObject.getClass().getName())) {//当前循环中图表操作不属于当前枚举ChartsEnum.getEnumByChartImplClazz(((XmlComplexContentImpl)xmlObject).getClass()).fillModel(chartModel, xmlObject, bias);return;}CTScatterChart chart = (CTScatterChart)xmlObject;List<CTScatterSer> serList = chart.getSerList();//更新数据区域for (int i = 0; i < serList.size(); i++) {//数据填充//CTScatterSer ser = chart.getSerArray(i);CTAxDataSource cat = ser.getXVal();CTNumDataSource val = ser.getYVal();this.dataAnalysisFill(chartModel,i,bias,cat,val);}}/*** 得到目标位置的图表* @param ctChart 可绘制区域图表* @param xmlObjSeat 目标图标位置位置* @return*/@Overridepublic XmlObject getTargetChart(int chartSeat, CTChart ctChart, int xmlObjSeat) {try {CTScatterChart scatterChart = ctChart.getPlotArea().getScatterChartArray(xmlObjSeat);return scatterChart;}catch (Exception e){throw new RuntimeException("当前位置【" + chartSeat + "】不存在【散点图】!!!");}}},;/*** 图表对象*/public Class<? extends XmlObject> chartClazz;/*** 图表实现对象*/public Class<? extends XmlComplexContentImpl> chartImplClazz;ChartsEnum(Class<? extends XmlObject> chartClazz,Class<? extends XmlComplexContentImpl> chartImplClazz){this.chartClazz = chartClazz;this.chartImplClazz = chartImplClazz;}/*** 填充模板数据* @param chartModel 图表和数据源* @param xmlObject 当前元素* @param bias 偏向值*/public abstract void fillModel(ChartModel chartModel,XmlObject xmlObject,int bias);/*** 得到目标位置的图表* @param chartSeat 位置* @param ctChart 可绘制区域图表* @param xmlObjSeat 目标图标位置位置*/public abstract XmlObject getTargetChart(int chartSeat,CTChart ctChart,int xmlObjSeat);/*** 根据值来源得到对应的 图表实现对象* @param chartImplClazz 图表实现对象* @return*/public static ChartsEnum getEnumByChartImplClazz(Class<? extends XmlComplexContentImpl> chartImplClazz){for (ChartsEnum value : ChartsEnum.values()) {if (value.getChartImplClazz().equals(chartImplClazz)){return value;}}return null;}/*** 根据值来源得到对应的 图表对象* @param chartClazz 图表对象* @return*/public static ChartsEnum getEnumByChartClazz(Class<? extends XmlObject> chartClazz){for (ChartsEnum value : ChartsEnum.values()) {if (value.getChartClazz().equals(chartClazz)){return value;}}return null;}/*** 刷新内置excel数据* @return*/public static boolean refreshExcel(ChartModel chartModel) throws IOException, InvalidFormatException {List<String> titleList = chartModel.getTitleList();List<String> numberList = chartModel.getNumberList();List<Map<String, String>> sourceModelList = chartModel.getSourceModelList();XWPFChart xwpfChart = chartModel.getXwpfChart();boolean result = true;Workbook wb = new XSSFWorkbook();Sheet sheet = wb.createSheet(chartModel.getSheetName());//根据数据创建excel第一行标题行for (int i = 0; i < titleList.size(); i++) {if (sheet.getRow(0) == null) {sheet.createRow(0).createCell(i).setCellValue(titleList.get(i) == null ? "" : titleList.get(i));} else {sheet.getRow(0).createCell(i).setCellValue(titleList.get(i) == null ? "" : titleList.get(i));}}//遍历数据行for (int i = 0; i < sourceModelList.size(); i++) {Map<String, String> baseFormMap = sourceModelList.get(i);//数据行//fldNameArr字段属性for (int j = 0; j < numberList.size(); j++) {if (sheet.getRow(i + 1) == null) {if (j == 0) {try {sheet.createRow(i + 1).createCell(j).setCellValue(baseFormMap.get(numberList.get(j)) == null ?"" : baseFormMap.get(numberList.get(j)));} catch (Exception e) {if (baseFormMap.get(numberList.get(j)) == null) {sheet.createRow(i + 1).createCell(j).setCellValue("");} else {sheet.createRow(i + 1).createCell(j).setCellValue(baseFormMap.get(numberList.get(j)));}}}} else {BigDecimal b = new BigDecimal(baseFormMap.get(numberList.get(j)));double value = 0D;if (b != null) {value = b.doubleValue();}if (value == 0D) {sheet.getRow(i + 1).createCell(j);} else {sheet.getRow(i + 1).createCell(j).setCellValue(b.doubleValue());}}}}// 更新嵌入的workbookList<POIXMLDocumentPart> pxdList = xwpfChart.getRelations();if(pxdList!=null&&pxdList.size()>0) {for (int i = 0; i < pxdList.size(); i++) {if (pxdList.get(i).toString().contains("sheet")) {POIXMLDocumentPart xlsPart = xwpfChart.getRelations().get(0);OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();try {wb.write(xlsOut);xlsOut.close();} catch (IOException e) {e.printStackTrace();result = false;} finally {if (wb != null) {try {wb.close();} catch (IOException e) {e.printStackTrace();result = false;}}}}}}return result;}/*** 数据分析* @param chartModel* @param i* @param bias* @param cat* @param val*/public void dataAnalysisFill (ChartModel chartModel,int i,int bias,CTAxDataSource cat,CTNumDataSource val) {//数据源List<Map<String, String>> sourceModelList = chartModel.getSourceModelList();//数据源keyList<String> numberList = chartModel.getNumberList();//CTStrData strData = cat.getStrRef().getStrCache();CTNumData numData = val.getNumRef().getNumCache();long idx = 0;for (int j = 0; j < sourceModelList.size(); j++) {//判断获取的值是否为空String value = "0";if (new BigDecimal(sourceModelList.get(j).get(numberList.get(i + 1))) != null) {value = new BigDecimal(sourceModelList.get(j).get(numberList.get(i + 1))).toString();}if (!"0".equals(value)) {CTNumVal numVal = numData.addNewPt();//序列值numVal.setIdx(idx);numVal.setV(value);}CTStrVal sVal = strData.addNewPt();//序列名称sVal.setIdx(idx);sVal.setV(sourceModelList.get(j).get(numberList.get(0)));idx++;}numData.getPtCount().setVal(idx);strData.getPtCount().setVal(idx);//赋值横坐标数据区域String axisDataRange = newCellRangeAddress(1, sourceModelList.size(), 0, 0).formatAsString(chartModel.getSheetName(), false);cat.getStrRef().setF(axisDataRange);//赋值纵坐标数据区域String numDataRange = newCellRangeAddress(1, sourceModelList.size(), i + 1 + bias, i + 1 + bias).formatAsString(chartModel.getSheetName(), false);val.getNumRef().setF(numDataRange);}}

工具类:图片写入

package com.wyz.world.utils;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** word图片*/
public class CustomXWPFDocument extends XWPFDocument{public CustomXWPFDocument(InputStream in) throws IOException {super(in);}public CustomXWPFDocument() {super();}public CustomXWPFDocument(OPCPackage pkg) throws IOException {super(pkg);}/*** @param id* @param width*            宽* @param height*            高* @param paragraph*            段落*/public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {final int EMU = 9525;width *= EMU;height *= EMU;String blipId = super.getRelationId(super.getAllPictures().get(id));CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();String picXml = ""+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"+ "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"+ "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"+ "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""+ id+ "\" name=\"Generated\"/>"+ "            <pic:cNvPicPr/>"+ "         </pic:nvPicPr>"+ "         <pic:blipFill>"+ "            <a:blip r:embed=\""+ blipId+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"+ "            <a:stretch>"+ "               <a:fillRect/>"+ "            </a:stretch>"+ "         </pic:blipFill>"+ "         <pic:spPr>"+ "            <a:xfrm>"+ "               <a:off x=\"0\" y=\"0\"/>"+ "               <a:ext cx=\""+ width+ "\" cy=\""+ height+ "\"/>"+ "            </a:xfrm>"+ "            <a:prstGeom prst=\"rect\">"+ "               <a:avLst/>"+ "            </a:prstGeom>"+ "         </pic:spPr>"+ "      </pic:pic>"+ "   </a:graphicData>" + "</a:graphic>";inline.addNewGraphic().addNewGraphicData();XmlToken xmlToken = null;try {xmlToken = XmlToken.Factory.parse(picXml);} catch (XmlException xe) {xe.printStackTrace();}inline.set(xmlToken);inline.setDistT(0);inline.setDistB(0);inline.setDistL(0);inline.setDistR(0);CTPositiveSize2D extent = inline.addNewExtent();extent.setCx(width);extent.setCy(height);CTNonVisualDrawingProps docPr = inline.addNewDocPr();docPr.setId(id);docPr.setName("图片名称");docPr.setDescr("描述信息");}
}

java使用poi操作world生成饼图,柱状图,折线图,组合图:二相关推荐

  1. java使用poi操作world生成饼图,柱状图,折线图,组合图:一

    java使用poi操作world生成饼图,柱状图,折线图,组合图:一 下文和问题链接 开发前准备 准备模板 模板下载地址百度云盘:cvod 本文可用操作 组合图操作 模板效果对比填充后的效果 饼图 模 ...

  2. java使用poi操作word模板,插入图片、段落、表格

    java使用poi操作word插入图片.段落.表格 其他链接 准备工作 创建word模板.docx文件 编写模板格式.xml文件 java上手poi maven依赖 使用到的包 具体应用 对应封装方法 ...

  3. 简单实现POI操作Excel生成数据透视图

    简单实现POI操作Excel生成数据透视图 需求 思考 尝试 实现 搞完收工,去画模板了 需求 财务部门需要做一自动导出数据报表的功能,其中要有指定格式的数据透视图(柱状图.饼状图等等) 思考 正常来 ...

  4. execle java,Java使用POI操作Excel

    Java使用POI操作Excel 1. POI操作Excel 1.1. 依赖 org.apache.poi poi 4.1.0 org.apache.poi poi-ooxml 4.1.0 org.a ...

  5. Java使用POI通过模板生成Word

    Java使用POI通过模板生成Word 前言 最近工作需要用到,所以记录下来以便查找. 一.概述 POI读写word使用的核心类是XWPFDocument.一个XWPFDocument代表一个docx ...

  6. java使用poi操作excel删除一整行

    java使用poi操作excel删除一整行 需求1:删除excel表格第4行 代码示例: sheet.shiftRows(4, sheet.getLastRowNum(),-1); 第一个参数为行数( ...

  7. Java使用poi操作ppt

    Java使用poi操作ppt https://editor.csdn.net/md/?articleId=117926694 上一篇中写了操作文本框和插入图片 这一篇主要是如何在有模板的情况下如替换文 ...

  8. Java使用poi操作excel注意事项

    Java使用poi操作excel注意事项 1.如果只需要获取sheet信息,用流模式打开文件即可获取,消耗内存少 2.上传的文件需要校验,防止Excel包含异常的缓存文件,缓存文件可能会有几百兆,会瞬 ...

  9. JAVA使用POI操作Excel表,XSSF(xlsx)和HSSF(xls)

    JAVA使用POI操作Excel表,XSSF(xlsx)和HSSF(xls) *** POI的结构: ---*HSSF - 提供读写Microsoft Excel格式档案的功能. ---*XSSF - ...

最新文章

  1. 国产搜索引擎首超Google 中文搜索瓦解霸权?
  2. 数据库中表id自增重置为1
  3. java中方法的参数传递
  4. windows 技术篇 - uispy 工具获取和使用,windows窗口属性快捷查看工具
  5. 极客精神|自制机械臂!被任正非表扬的华为天才少年
  6. 拉格朗日插值法(Lagrange)
  7. 7.0上的新KIE持久性API
  8. table 鼠标移上去改变单元格边框颜色。
  9. 【计算机网络复习 数据链路层】3.4.3 后退N帧协议(GBN)
  10. 聊聊var与let 在window下面的区别(除开作用域)
  11. OpenResty HelloWorld
  12. 第二周冲刺第一天个人博客
  13. FZU 1502 Letter Deletion
  14. android qq毛玻璃,如何快速做出毛玻璃背景?有了这个网格渐变神器,1分钟搞定...
  15. CentOS7图形界面和命令行界面的切换快捷键
  16. Thinkphp使用CKEditor4富文本编辑器
  17. 计算机主机的cpu,台式机cpu能换吗?台式电脑换cpu的详细步骤
  18. 社会工程学之从微信取名看性格
  19. Warshell算法实现
  20. (附源码)计算机毕业设计SSM基于ETC用户的自驾游推荐系统

热门文章

  1. 创业者在创业之初都需要做哪些准备工作呢
  2. 小白学习Winform 遇到的问题总结
  3. AE圣诞树(html版本),免费
  4. 关于开发人员学习的网站【收藏】
  5. 《Cocos Creator游戏实战》滚动数字
  6. linux 搜狗输入法 太慢,【分享】ibus使用搜狗输入法词库后,反应慢的解决方法...
  7. Xmind基础教程-保存到印象笔记
  8. 北京大学肖臻老师《区块链技术与应用》ETH笔记 - 5.0 ETH中GHOST协议篇
  9. PKUSC 模拟赛 day1 下午总结
  10. 乐淘CEO毕胜:PPIC周报机制