java
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.*;
/**
* Html转Word
* @author hjj
*/
public static MultipartFile htmlToWord(String html,String filePath) throws Exception {
// 1.生成文件名称
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = filePath+"/"+"LangChain" + sdf.format(new Date())+".doc";
// 返回MyltipartFile类
MultipartFile multipartFile = null;
if (StringUtils.isNotEmpty(html)) {
// 2.创建一个新的文档
XWPFDocument document = new XWPFDocument();
// 3.创建段落并添加文本内容
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(html);
// 4.保存文档到文件
try (FileOutputStream out = new FileOutputStream(fileName)) {
document.write(out);
System.out.println("成功创建doc文件!");
// 关闭流
out.close();
document.close();
} catch (IOException e) {
e.printStackTrace();
}
// 5.获取文件信息 Get File information
File tempFile = new File(fileName);
// 6.Create a FileInputStream from the file
FileInputStream input = new FileInputStream(tempFile);
// 7.Create a MultipartFile using MockMultipartFile
multipartFile = new MockMultipartFile(
"file",
tempFile.getName(),
"application/msword",
input
);
}
return multipartFile;
}