package com.iauto.soa.file.controller;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class WordUtils {
private final static Logger log = LoggerFactory.getLogger(WordUtils.class);
/**
* 创建文件
*
* @param path 路径
* @param fileName 文件名
*/
public static void createWord(String path, String fileName){
//判断目录是否存在
File file = new File(path);
//exists()测试此抽象路径名表示的文件或目录是否存在。
if (!file.exists()) {
if(!file.mkdirs()){
throw new RuntimeException("创建文件路径失败");
}
}
//因为HWPFDocument并没有提供公共的构造方法 所以没有办法构造word
//这里使用word2007及以上的XWPFDocument来进行构造word
@SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument();
try(OutputStream stream = new FileOutputStream(new File(file, fileName))){
document.write(stream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 写入文件
*
* @param path 路径
* @param data 数据
*/
public static void writeDataDocx(String path, String data){
try(OutputStream outputStream = new FileOutputStream(path)){
try(XWPFDocument document = new XWPFDocument()){
//添加一个段落
XWPFParagraph p1 = document.createParagraph();
//---首行缩进,指定额外的缩进,应适用于父段的第一行。
p1.setIndentationFirstLine(800);
//p1.createRun()将一个新运行追加到这一段
XWPFRun r1 = p1.createRun();
r1.setText(data);
XWPFParagraph p2 = document.createParagraph();
//---首行缩进,指定额外的缩进,应适用于父段的第一行。
p2.setIndentationFirstLine(800);
document.write(outputStream);
}
log.info("创建word成功");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出信息到word文档
*
* @param data 错误信息
*/
public static void errorMsg2Word(String data){
String path;
String fileName = "message.docx";
try {
path = ResourceUtils.getURL("classpath:").getPath()+"templates/";
}catch (Exception e){
throw new RuntimeException(e);
}
String filePath = path + fileName;
log.info("<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>"+filePath);
//创建word
WordUtils.createWord(path,fileName);
//写入数据
WordUtils.writeDataDocx(filePath,data);
}
}