1 修改pom.xml,导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/>
</parent>
<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>
2 在src/resources下创建export.docx模板
{{department}}
{{person}}
{{time}}
{{img}}
表格内容
{{$fe:list t.name}} {{t.age}}
3 创建工具类
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;
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();
}
}
}
- JFreeChart画图工具类JFreeChartToFileUtil.java
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}:sum
plot.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();
}
}
}
4 控制器类ExportController.java
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 java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
@RestController
public 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);
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\\abc\\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);
}
}
5 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WordExportApplication {
public static void main(String[] args) {
SpringApplication.run(WordExportApplication.class, args);
}
}
网友评论