分享

java word操作

 wenxuefeng360 2022-08-31 发布于四川

1.java复制文件

savepath:D:\\

Files.copy(Paths.get(savePath+"mould\\mould.doc"), new FileOutputStream(savePath+"dayplan\\1111.doc"));

2.调用本地office打开word

Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler "  + "d:\\dayplan\\1111.doc");

3.替换word数据

详见:java修改Word文档内容

pom:

 <!--poi支持-->
        <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>3.10-FINAL</version>
        </dependency>
        <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>3.10-FINAL</version>
        </dependency>

 

Map map=new HashMap();
            map.put("name","admin");//${name}
            map.put("age","24");//${age}
            map.put("sex","男");//${sex}
            CreatWordByModel("f:/test.doc",map,"f:/test2.doc");

 

public static void CreatWordByModel(String  tmpFile, Map<String, String> contentMap, String exportFile) throws Exception{

        InputStream in = null;
        in = new FileInputStream(new File(tmpFile));

        HWPFDocument document = null;
        document = new HWPFDocument(in);
        // 读取文本内容
        Range bodyRange = document.getRange();
        System.out.println(bodyRange.toString());
        System.out.println(bodyRange.text());
        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }

        //导出到文件
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write((OutputStream)byteArrayOutputStream);
            OutputStream outputStream = new FileOutputStream(exportFile);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多