300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java使用poi操作world生成饼图 柱状图 折线图 组合图:二

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

时间:2023-04-28 02:02:29

相关推荐

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

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><!-- /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>mons</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>mons</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.x.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@ToStringpublic 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.x.chart.*;import org.openxmlformats.schemas.drawingml.x.chart.impl.CTBarChartImpl;import org.openxmlformats.schemas.drawingml.x.chart.impl.CTLineChartImpl;import org.openxmlformats.schemas.drawingml.x.chart.impl.CTPieChartImpl;import org.openxmlformats.schemas.drawingml.x.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@Getterpublic 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.x.main.CTNonVisualDrawingProps;import org.openxmlformats.schemas.drawingml.x.main.CTPositiveSize2D;import org.openxmlformats.schemas.drawingml.x.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=\"/drawingml//main\">"+ " <a:graphicData uri=\"/drawingml//picture\">"+ "<pic:pic xmlns:pic=\"/drawingml//picture\">"+ " <pic:nvPicPr>" + " <pic:cNvPr id=\""+ id+ "\" name=\"Generated\"/>"+ " <pic:cNvPicPr/>"+ " </pic:nvPicPr>"+ " <pic:blipFill>"+ " <a:blip r:embed=\""+ blipId+ "\" xmlns:r=\"/officeDocument//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("描述信息");}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。