超简单java导出word文档带图片,复制直接使用

使用freemarker生成word文档

借鉴sunshtwe作者的博客

第一步

  1. 你需要准备一个word模板,就是word文件,.doc或者.docx都可以,如果是图片你需要提前在word文件中插插入图片具体看以下图片, 是一个占位符,实际作用跟 j s p 的 {}是一个占位符,实际作用跟jsp的 是一个占位符,实际作用跟jsp{}的差不多就是传递数据,里面的变量随便写后期传的时候名字一致就可以

在这里插入图片描述

  1. 把这个word文件另存为xml格式,具体的另存在word中操作,然后使用在线xml工具,推荐使用在线 XML 格式化 | 菜鸟工具 (runoob.com),这一步主要是在xml文件中的是乱码,使用在线工具格式化就能编辑了,其次找到插入照片的地方,将二进制数据删除换成占位符 变量随便写,最好使用 {}变量随便写,最好使用 变量随便写,最好使用{image},最后创建xxx.ftl文件将这个编辑好的内容复制到xxx.ftl文件,注意会出现占位符不在一起的情况手动编辑一下就可以了,将多余的删除

在这里插入图片描述

占位符不在一起的情况

在这里插入图片描述

第二步

下面两个类直接复制

/**
 * 将图片转码为base64
 * @author: xxl
 * @since: 2023/6/8
 * @description: 图片工具类
 */
public class ImageUtil {
    /**
     * 将图片内容转换成Base64编码的字符串
     * @param imageFile 图片文件的全路径名称
     * @return 转换成Base64编码的图片内容字符串
     */
    public static String getImageBase64String(String imageFile) {
        if (ObjectUtil.isNull(imageFile)) {
            return "";
        }
        File file = new File(imageFile);
        if (!file.exists()) {
            return "";
        }
        InputStream is = null;
        byte[] data = null;
        try {
            is = new FileInputStream(file);
            data = new byte[is.available()];
            is.read(data);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeBase64String(data);
    }

}
/**
 * word文档工具类
 * @author xxl
 * @since 2023/6/7
 */
@Component
public class WordUtil {
    /**
     * 使用FreeMarker自动生成Word文档
     * @param dataMap  生成Word文档所需要的数据
     * @param fileName 生成Word文档的全路径名称,带文件名
     */
    public  void generateWord(Map<String, Object> dataMap,String fileName,String basePath,String templateName) throws Exception {
        // 设置FreeMarker的版本和编码格式
        Configuration configuration = new Configuration(new Version("2.3.30"));
        configuration.setDefaultEncoding("UTF-8");
        // 设置FreeMarker生成Word文档所需要的模板的路径 C:\\测试word文件夹
        configuration.setDirectoryForTemplateLoading(new File(basePath));
        // 设置FreeMarker生成Word文档所需要的模板
        Template t = configuration.getTemplate(templateName, "UTF-8");
        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8));
        //FreeMarker使用Word模板和数据生成Word文档
        t.process(dataMap, out);
        out.flush();
        out.close();
    }
}

测试类,下面的map的键对应上面占位符中变量,注意导出的文件的后缀是.doc,否则打不开

/**
 *  测试word工具类
 * @author xxl
 * @since  2023/6/8
 */
@SpringBootTest
class WordUtilTest {
    
    @Resource
    WordUtil wordUtil;
       public   String templateName = "word模板.ftl";
    public   String basePath = "D:\\Program Files (x86)\\idea\\IDEAproject\\work\\KYDX-Registration-System\\src\\main\\resources\\word\\";
    @Test
    void generateWord() throws Exception {
        //导出的位置+文件名
        final String name = "C:\\Users\\xxl\\Desktop\\test\\报名表.doc";
        //图片名
        final String imagePath = "D:\\Program Files (x86)\\idea\\IDEAproject\\work\\KYDX-Registration-System\\src\\main\\resources\\static\\photos\\gril7.jpeg";
        HashMap<String, Object> map = new HashMap<>();
        map.put("realName","许小亮");
        map.put("gender","男");
        map.put("nation","中国矿业大学专职辅导员应聘报名表");
        map.put("position","中国矿业大学专职辅导员应聘报名表");
        map.put("idCardNumber","中国矿业大学专职辅导员应聘报名表");
        map.put("englishProficiency","中国矿业大学专职辅导员应聘报名表");
        map.put("politicalOutlook","中国矿业大学专职辅导员应聘报名表");
        map.put("partyJoiningTime","中国矿业大学专职辅导员应聘报名表");
        map.put("phoneNumber","中国矿业大学专职辅导员应聘报名表");
        map.put("email","中国矿业大学专职辅导员应聘报名表");
        map.put("homeLocation","中国矿业大学专职辅导员应聘报名表");
        map.put("currentLocation","中国矿业大学专职辅导员应聘报名表");
        map.put("civilServiceExam","中国矿业大学专职辅导员应聘报名表");
        map.put("personalExperience","中国矿业大学专职辅导员应聘报名表");
        map.put("studentLeadershipExperience","中国矿业大学专职辅导员应聘报名表");
        map.put("academicHonors","中国矿业大学专职辅导员应聘报名表");
        map.put("disciplinaryRecord","中国矿业大学专职辅导员应聘报名表");
        map.put("image", ImageUtil.getImageBase64String(imagePath));
        wordUtil.generateWord(map,name,basePath,templateName);
    }
}

导出结果

在这里插入图片描述

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Java导出水印的Word文档,可以使用Apache POI库来创建和编辑Word文档。下面是一个简单的示例代码: ```java import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.PositionOffset; import org.apache.poi.xwpf.usermodel.VerticalAlign; import org.apache.poi.xwpf.usermodel.XWPFHeaderFooterPolicy; import org.apache.poi.xwpf.usermodel.XWPFHeader; import org.apache.poi.xwpf.usermodel.XWPFWatermark; public class WordDocumentExporter { public static void exportDocument(String fileName) { try { XWPFDocument document = new XWPFDocument(); // Add content to the document XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("This is a sample text."); // Add watermark to the document XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy(); if (policy == null) { policy = document.createHeaderFooterPolicy(); } XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); XWPFParagraph watermark = header.createParagraph(); watermark.setAlignment(ParagraphAlignment.CENTER); watermark.setVerticalAlignment(TextAlignment.CENTER); XWPFRun watermarkRun = watermark.createRun(); watermarkRun.setText("CONFIDENTIAL"); watermarkRun.setFontSize(72); watermarkRun.setColor("000000"); watermarkRun.setBold(true); watermarkRun.setItalic(true); CTBackground background = watermark.getCTP().addNewBackground(); CTShd shd = background.addNewShd(); shd.setFill("FFFFFF"); shd.setColor("FFFFFF"); shd.setVal(STShd.CLEAR); // Save the document FileOutputStream out = new FileOutputStream(fileName); document.write(out); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 在上面的代码中,我们首先创建了一个XWPFDocument对象,然后添加了一些文本内容。接下来,我们使用XWPFHeaderFooterPolicy和XWPFHeader类来创建文档的页眉,并在其中添加水印。在这个例子中,我们添加了一个“CONFIDENTIAL”水印,但你可以根据需要修改水印的文本和样式。最后,我们将文档保存到指定的文件中。 需要注意的是,导出水印的Word文档需要使用POI的最新版本,因为早期版本可能无法正确处理水印。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值