MrShi
2025-01-06 e1ec365640eefdcb06abb1d73da0d80367f79be3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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;
    }
 
 
 
}