package com.doumee.cloud.board;
|
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
|
import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
|
/**
|
* Created by IntelliJ IDEA.
|
*
|
* @Author : Rk
|
* @create 2025/1/3 9:11
|
*/
|
public class ExcelTestDemo {
|
|
public static void main(String[] args) {
|
modifyWordTemplate("https://bdreport.oss-cn-beijing.aliyuncs.com/xczl/20250103/temp/F0F4B90E185A4A9BA2147841B90F3909.docx", "d://output.docx", "张三", "Java课程");
|
}
|
|
public static void modifyWordTemplate(String templatePath, String outputPath, String name, String product) {
|
try (
|
// FileInputStream fis = new FileInputStream(templatePath);
|
XWPFDocument document = new XWPFDocument(getFileInputStream(templatePath))) {
|
// 此处连接到后续替换步骤
|
// 遍历段落
|
for (XWPFParagraph paragraph : document.getParagraphs()) {
|
for (XWPFRun run : paragraph.getRuns()) {
|
// 替换占位符
|
String text = run.getText(0);
|
if (text != null) {
|
text = text.replace("{{name}}", name)
|
.replace("{{text}}", product);
|
run.setText(text, 0); // 重新设置文本
|
}
|
}
|
}
|
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
|
document.write(fos); // 将修改后的文档写入输出流
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/*读取网络文件*/
|
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;
|
}
|
|
|
|
}
|