(导出可以有很多方式 这里用的Apache Api (之后可以尝试Easypoi))
run.addCarriageReturn();//硬回车
run.addBreak(); //软回车
1.在pom文件中加入
<!-- POI excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
(版本号3.18 与5.0.0冲突 如果出现版本问题改到4.1.1即可)
2.controller层要添加@RestController注解
3.方法上用@GetMapping
4.
//生成文档
XWPFDocument document = new XWPFDocument();
XWPFParagraph titleParagraph = document.createParagraph();
//设置标题居中
titleParagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun runTitle = titleParagraph.createRun();
//设置内容
runTitle.setText("zhangsan");
//是否加粗
runTitle.setBold(true);
//设置字号
runTitle.setFontSize(16);
5.导出图片
//文件输入流
FileInputStream fileInputStream = saveUrlAs(imageUrl, name);
XWPFParagraph pic = document.createParagraph();
pic.setAlignment(ParagraphAlignment.CENTER);
XWPFRun picRun = pic.createRun();
picRun.addPicture(
fileInputStream, ImageTypeEnum.getByValue(suffix).getDocumentType(),
name,
Units.toEMU(450),
Units.toEMU(300)
);
6.文件输出流
public static FileInputStream saveUrlAs(String photoUrl, String fileName) {
try {
URL url = new URL(photoUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
FileInputStream fileInputStream = new FileInputStream(fileName);
return fileInputStream;
}
catch (Exception e) {
log.error("Exception",e);
return null;
}
}
7.浏览器下载
//二进制输出流
ByteArrayOutputStream bass = new ByteArrayOutputStream();
document.write(bass);
document.close();
//二进制输入流
ByteArrayInputStream in = new ByteArrayInputStream(bass.toByteArray());
//下载文件
FileUtil.downFile(InputStream in, String fileName, HttpServletResponse response);