1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java使用easypoi导出word文档 包含图片 表格 文字;

java使用easypoi导出word文档 包含图片 表格 文字;

时间:2022-02-19 00:25:28

相关推荐

java使用easypoi导出word文档 包含图片 表格 文字;

添加依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>word-export</artifactId><version>0.0.1-SNAPSHOT</version><name>word-export</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.jfree</groupId><artifactId>jfreechart</artifactId><version>1.0.19</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>4.4.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

ExportUtil类

package com.example.wordexport.utils;import cn.afterturn.easypoi.word.WordExportUtil;import org.apache.poi.xwpf.usermodel.XWPFDocument;import java.io.File;import java.io.FileOutputStream;import java.util.Map;/*** @author chenbin* @date /10/11*/public class ExportUtil {public static void export(Map<String, Object> map, String url, File tempFile) {try {XWPFDocument doc = WordExportUtil.exportWord07(url, map);FileOutputStream fos = new FileOutputStream(tempFile);doc.write(fos);fos.close();} catch (Exception e) {e.printStackTrace();}}}

JFreeChartToFileUtil类

package com.example.wordexport.utils;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.ValueAxis;import org.jfree.chart.labels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PiePlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.data.general.DefaultPieDataset;import java.awt.*;import java.io.File;public class JFreeChartToFileUtil {public static void createPieChart(DefaultPieDataset pds, File file,String title) {try {// 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接JFreeChart chart = ChartFactory.createPieChart(title, pds, false, false, true);// 如果不使用Font,中文将显示不出来Font font = new Font("宋体", Font.BOLD, 12);// 设置图片标题的字体chart.getTitle().setFont(font);// 得到图块,准备设置标签的字体PiePlot plot = (PiePlot) chart.getPlot();// 设置标签字体plot.setLabelFont(font);plot.setStartAngle(3.14f / 2f);// 设置plot的前景色透明度plot.setForegroundAlpha(0.7f);// 设置plot的背景色透明度plot.setBackgroundAlpha(0.0f);// 设置标签生成器(默认{0})// {0}:key {1}:value {2}:百分比 {3}:sumplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}占{2}"));// 将内存中的图片写到本地硬盘ChartUtilities.saveChartAsJPEG(file, chart, 600, 300);} catch (Exception e) {e.printStackTrace();}}public static void createBarChart(CategoryDataset pds, File file,String title) {try {// 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接JFreeChart chart = ChartFactory.createBarChart3D(title, null,null, pds, PlotOrientation.VERTICAL,true, true, true);// 如果不使用Font,中文将显示不出来Font font = new Font("宋体", Font.BOLD, 12);// 设置图片标题的字体chart.getTitle().setFont(font);chart.getLegend().setItemFont(font);// 得到图块,准备设置标签的字体CategoryPlot plot = (CategoryPlot) chart.getPlot();// 设置plot的前景色透明度plot.setForegroundAlpha(0.7f);// 设置plot的背景色透明度plot.setBackgroundAlpha(0.0f);// 设置标签生成器(默认{0})ValueAxis rangeAxis = plot.getRangeAxis();CategoryAxis domainAxis = plot.getDomainAxis();rangeAxis.setLabelFont(font);rangeAxis.setTickLabelFont(font);domainAxis.setLabelFont(font);domainAxis.setTickLabelFont(font);domainAxis.setMaximumCategoryLabelLines(10);domainAxis.setMaximumCategoryLabelWidthRatio(0.5f);// 将内存中的图片写到本地硬盘ChartUtilities.saveChartAsJPEG(file, chart, 600, 300);} catch (Exception e) {e.printStackTrace();}}}

ExportController类

package com.example.wordexport.controller;import cn.afterturn.easypoi.entity.ImageEntity;import com.example.wordexport.utils.ExportUtil;import com.example.wordexport.utils.JFreeChartToFileUtil;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.data.general.DefaultPieDataset;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;import java.io.*;import .URL;import .URLEncoder;import java.nio.charset.StandardCharsets;import java.util.*;/*** @author chenbin* @date /10/11*/@RestControllerpublic class ExportController {@RequestMapping("export")public void export(HttpServletResponse response) throws IOException {response.setContentType("application/msword");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试.docx", StandardCharsets.UTF_8.name()));OutputStream outputStream = response.getOutputStream();Map<String, Object> map = new HashMap<String, Object>();putBaseInfo(map);//putImg(map);putList(map);zhuzhuangtu(map);//putBar(map);String url = Objects.requireNonNull(getClass().getClassLoader().getResource("export.docx")).getPath();File tempFile = File.createTempFile("tempDoc", ".docx");ExportUtil.export(map, url, tempFile);InputStream in = new FileInputStream(tempFile);//创建存放文件内容的数组byte[] buff = new byte[1024];//所读取的内容使用n来接收int n;//当没有读取完时,继续读取,循环while ((n = in.read(buff)) != -1) {//将字节数组的数据全部写入到输出流中outputStream.write(buff, 0, n);}//强制将缓存区的数据进行输出outputStream.flush();//关流outputStream.close();in.close();tempFile.deleteOnExit();}private void putBaseInfo(Map<String, Object> map) {map.put("department", "Easypoi");map.put("person", "JueYue");map.put("time", "234234");}private void putImg(Map<String, Object> map) {ImageEntity image = new ImageEntity();image.setHeight(200);image.setWidth(500);image.setUrl("C:\\Users\\chenbin\\Pictures\\1.jpg");image.setType(ImageEntity.URL);map.put("img", image);}private void putBar(Map<String, Object> map) throws IOException {File file2 = File.createTempFile("temp", "jpg");DefaultPieDataset pds = new DefaultPieDataset();pds.setValue("上市公司股票", 100);pds.setValue("非上市公司股权", 200);pds.setValue("传统不良债权", 300);pds.setValue("抵债资产", 400);pds.setValue("投资性房地产", 500);pds.setValue("长期股权投资", 600);JFreeChartToFileUtil.createPieChart(pds, file2, "账面价值比例");ImageEntity image = new ImageEntity();image.setHeight(200);image.setWidth(500);System.out.println(file2.getAbsolutePath());image.setUrl(file2.getAbsolutePath());image.setType(ImageEntity.URL);map.put("img", image);}public void zhuzhuangtu(Map<String, Object> dataMap) throws IOException {File file2 = File.createTempFile("temp", "jpg");DefaultCategoryDataset dataset = new DefaultCategoryDataset();List<String> nameList = new ArrayList<>();nameList.add("广东省");nameList.add("河南省");nameList.add("内蒙古自治区");nameList.add("黑龙江省");nameList.add("新疆");nameList.add("湖北省");nameList.add("辽宁省");nameList.add("山东省");nameList.add("陕西省");nameList.add("上海市");nameList.add("贵州省");nameList.add("重庆市");nameList.add("西藏自治区");nameList.add("安徽省");nameList.add("福建省");nameList.add("湖南省");nameList.add("海南省");nameList.add("江苏省");nameList.add("广西");nameList.add("宁夏");nameList.add("青海省");nameList.add("江西省");nameList.add("浙江省");nameList.add("山西省");nameList.add("四川省");nameList.add("香港特别行政区");nameList.add("澳门特别行政区");nameList.add("云南省");nameList.add("北京市");nameList.add("天津市");nameList.add("吉林省");List<String> areaList = new ArrayList<>();nameList.forEach(i -> {if (i.contains("省")) {areaList.add(i.replace("省", ""));} else if (i.contains("特别行政区")) {areaList.add(i.replace("特别行政区", ""));} else if (i.contains("市")) {areaList.add(i.replace("市", ""));} else if (i.contains("自治区")) {areaList.add(i.replace("自治区", ""));} else {areaList.add(i);}});areaList.forEach(i -> {dataset.setValue(23434, "账面价值", i);});areaList.forEach(i -> {dataset.setValue(34234234, "估值结果", i);});JFreeChartToFileUtil.createBarChart(dataset, file2, "资产结果");ImageEntity image = new ImageEntity();image.setHeight(200);image.setWidth(500);System.out.println(file2.getAbsolutePath());image.setUrl(file2.getAbsolutePath());image.setType(ImageEntity.URL);dataMap.put("img", image);}private void putList(Map<String, Object> map) {List<Map<String, String>> list = new ArrayList<>();for (int i = 0; i < 10; i++) {Map<String, String> map1 = new HashMap<>();map1.put("name", "xiao");map1.put("age", "12");list.add(map1);}map.put("list", list);}}

模板

导出结果

源码地址

/zhang_chen_bin/word-export

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