package com.doumee.core.excel;
|
|
import com.doumee.core.constants.ResponseStatus;
|
import com.doumee.core.exception.BusinessException;
|
import com.doumee.core.utils.Constants;
|
import com.doumee.dao.business.model.YwTempConfig;
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.*;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLEncoder;
|
import java.nio.charset.Charset;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
* Created by IntelliJ IDEA.
|
*
|
* @Author : Rk
|
* @create 2025/1/3 9:11
|
*/
|
public class ExcelReplaceCommon {
|
|
// public static void main(String[] args) {
|
// modifyWordTemplate("https://bdreport.oss-cn-beijing.aliyuncs.com/xczl/20250110/temp/BE9C167EE35C40E78029C68BABBD0EAB.docx", "d://output.docx", "张三", "Java课程");
|
// }
|
|
|
|
|
|
public static String modifyWordTemplate(String templatePath, List<YwTempConfig> ywTempConfigList,String fileName) {
|
try (
|
XWPFDocument document = new XWPFDocument(getFileInputStream(templatePath))) {
|
// 此处连接到后续替换步骤
|
// 遍历段落
|
for (XWPFParagraph paragraph : document.getParagraphs()) {
|
for (XWPFRun run : paragraph.getRuns()) {
|
// 替换占位符
|
String text = run.getText(0);
|
if (text != null) {
|
for (YwTempConfig ywTempConfig:ywTempConfigList
|
) {
|
text = text.replace(ywTempConfig.getTitle(), ywTempConfig.getUrl());
|
}
|
run.setText(text, 0); // 重新设置文本
|
}
|
}
|
}
|
String path = "d://"+fileName;
|
try (FileOutputStream fos = new FileOutputStream(path)) {
|
document.write(fos); // 将修改后的文档写入输出流
|
}
|
return path;
|
/*//二进制OutputStream
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
document.write(baos);//文档写入流
|
//OutputStream写入InputStream二进制流
|
ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray()); */
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"文件转换异常!");
|
}
|
|
/*读取网络文件*/
|
public static InputStream getFileInputStream(String path) {
|
URL url = null;
|
try {
|
url = new URL(path);
|
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
//设置超时间为3秒
|
conn.setConnectTimeout(3*1000);
|
//防止屏蔽程序抓取而返回403错误
|
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
|
//得到输入流
|
return conn.getInputStream();
|
} catch (Exception e) {
|
|
}
|
return null;
|
}
|
|
|
|
}
|