导出word并遍历数据和图片

一.条件:可根据个人情况更改与下面部分代码结合.
1.建一个test.docx文档.
内容:
clipboard.png

另保存为test.xml.重命名为test.ftl.把test.ftl放入项目指定位置.并修改test.ftl.

clipboard.png

clipboard.png

clipboard.png

二.后端实现代码(测试用):

1.word操作工具类.

public class WordUtil {
private static Logger log = Logger.getLogger(WordUtil.class);
/**
 * @Desc:生成word文件
 * @paramdataMap word中需要展示的动态数据,用map集合来保存
 * @paramtemplateName word模板名称,例如:test.ftl
 * @paramfilePath文件生成的目标路径,例如:C:/
 * @paramfileName生成的文件名称,例如:test.doc
 * */
public static void createWord(Map<String, Object>dataMap,String templateName,String filePath,String fileName){
    try {
//创建配置实例
        Configuration configuration = new Configuration();
//设置编码
        configuration.setDefaultEncoding("UTF-8");
//ftl模板文件
       /* File file = new File(filePath);
        configuration.setDirectoryForTemplateLoading(file);*/
        configuration.setClassForTemplateLoading(WordUtil.class,"/templates/generator/");//ftl固定存储位置
//获取模板
        Template template = configuration.getTemplate(templateName);
//输出文件
        /*File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        File outFile = new File(desktopPath + File.separator + fileName);//输出到桌面*/
        
        File outFile = new File(filePath + File.separator + fileName);
//如果输出目标文件夹不存在,则创建
        if (!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }
//将模板和数据模型合并生成文件
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
        template.process(dataMap, out);
//关闭流
        out.flush();
        out.close();
    } catch (Exception e) {
        log.error("生成 word文档(WordUtil)出错:[msg:"+e.getMessage()+"] ,文件名:" + fileName);
        e.printStackTrace();
    }
}
/** 文件下载
 * @param path 文件路径全路径,包含文件名
 * @param response
 * @return
 * */
public static HttpServletResponse downFile(String path, HttpServletResponse response) {
    try {
// path是指欲下载的文件的路径。
        File file = new File(path);
// 取得文件名。
        String filename = file.getName();
// 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
// 清空response
        response.reset();
// 设置response的Header
        String fileName = URLEncoder.encode(filename,"UTF-8");
        if(fileName.length()>150){ 
            fileName=new String(filename.getBytes("GBK"),"ISO-8859-1"); }
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outs = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outs.write(buffer);
        outs.flush();
        outs.close();
        file.delete();
    }catch (IOException e) {
        log.error("下载文档(WordUtil)出错:[msg:"+e.getMessage()+"] "); e.printStackTrace(); }
    return response;
}

}

2.控制层

@RequestMapping("downWord")
public void DownWord(HttpServletRequest request, String response) throws IOException {
    List<TrainScore> info = new ArrayList<TrainScore>();
//测试数据,也可以从数据库中提取
    for(int i=0;i<3;i++){
        TrainScore ts = new TrainScore();
        ts.setId("12345667"+i);
        ts.setUserId("91345678"+i);
        ts.setTrainId("3456789"+i);
        ts.setScore(90+i);
        ts.setComment("测试"+i);
        info.add(ts);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("title","用户考核表数据");
    params.put("info",info);
 //我的图片位置images/timg.png
    params.put("image",getImageBase("images/timg.png",request));
    params.put("attention","请注意确保所有信息的正确性");
    WordUtil wordUtil = new WordUtil();
    wordUtil.createWord(params,"test.ftl","C:/","test.doc");

}

//获得图片路径和base64编码
private String  getImageBase(String src,HttpServletRequest request) {
    if(src==null||src==""){
        return "";
    }
 //图片在项目中的路径
    File file = new File(request.getSession().getServletContext().getRealPath("/")+src.replace(request.getSession().getServletContext().getContextPath(),""));
    if(!file.exists()) {
        return "";
    }
    InputStream in = null;
    byte[] data = null;
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    try {
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
//加密
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);
}

三.运行结果:

clipboard.png

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java中实现Word模板导出List的过程需要使用特定的工具和技术: 1. 基于JDBC的操作类库,如poi 2. 针对Word操作的类库,如Apache POI 3. 基于XML技术的Word文件渲染库,如Freemarker 4. 使用Java语言的数据结构和算法,如List和循环 5. 熟悉Word文档的XML文件结构和样式定义 在实现Word模板导出List的过程中,首先需要创建一个基于XML的Word模板。通过Java程序读取该模板,获取需要填充的位置。然后,使用数据结构和算法,将List中的数据在对应位置进行填充。 同时,需要掌握Java操作Word的相关技术,如通过Apache POI读取和操作Word文档内容,以及使用Freemarker等XML渲染库进行数据填充。最终,将填充好数据Word文档进行保存和输出即可。 总之,实现Java操作Word模板导出List需要掌握相关的技术和工具,同时理解Word文档的XML结构和样式定义,才能达到高效、准确地实现填充Word模板的目的。 ### 回答2: 随着信息化的发展,我们越来越多地使用电脑来处理文档,而word作为一个重要的文档处理工具,在我们的生活和工作中占据着非常重要的位置。在实际操作中,我们经常会遇到要将特定数据填充到word模板中的情况。如果每次都手动修改和导出word文档,就显得非常繁琐和耗时,此时我们可以采用使用java来实现批量导出word模板。 要实现这个功能,需要注意以下几点: 1.首先,需要有一个word模板,里面需要提前设置好需要填充内容的位置,区域可以通过设置书签进行标记。 2.然后,需要将需要填充到word模板中的数据存入到list中,list中的每一个元素,对应着word模板中需要填充的内容。 3.使用poi-tl这个jar包,进行word模板的导出。poi-tl可以按照模板文件中的书签对word模板进行填充,从而生成导出word文档。 4.在进行导出的过程中,需要注意一些细节问题,如导出文件的存储位置,文件名的定义和格式等等。 接下来,我们将使用以下代码来演示如何实现这一功能: ``` //定义导出word文档的存储位置和文件名 String filePath = "D:\\temp\\" + fileName + ".docx"; //开始导出文件 OutputStream os = new FileOutputStream(filePath); //读取模板文件 InputStream is = new FileInputStream("D:\\temp\\template.docx"); //使用poi-tl核心类进行导出操作 XWPFTemplate template = XWPFTemplate.compile(is).render(data); template.write(os); template.close(); os.flush(); os.close(); is.close(); ``` 其中,fileName代表导出文件的文件名,data代表存储数据的list。 最后,总体来说,使用java实现word模板导出list,可以大大提高我们的工作效率,避免手动修改文档的繁琐过程,是一项非常实用的技能。 ### 回答3: 在Java中实现Word模板导出list涉及到如下几个步骤: 1. 准备Word模板 首先需要准备好要导出数据Word模板文档,可以使用Microsoft Word等办公软件创建。 2. 设计数据结构 为了让程序能够更方便地处理数据,需要设计出适合的数据结构。在此例中,我们可以创建一个Java对象,用于存储每个要填充的文本域,例如: public class WordData { private String field1; private String field2; // getter and setter methods // ... } 3. 填充模板 要填充模板,我们可以使用Apache POI库(一个开源的Java库,用于处理Microsoft Office格式的文档),它提供了对Word文档的访问和操作功能。通过POI,我们可以读入Word模板,扫描它的所有内容,并用Java代码替换其中指定的文本域。 首先需要创建一个XWPFDocument对象,然后通过它获取模板中的所有XWPFParagraph和XWPFTable元素,然后遍每个元素,查找和替换指定文本域。例如: XWPFDocument doc = new XWPFDocument(new FileInputStream("template.docx")); List<XWPFParagraph> paragraphs = doc.getParagraphs(); List<XWPFTable> tables = doc.getTables(); for (XWPFParagraph paragraph : paragraphs) { String text = paragraph.getText(); if (text.contains("${field1}")) { // 替换文本域 text = text.replace("${field1}", wordData.getField1()); paragraph.getCTP().getPList().get(0).setRArray(0, new XWPFRun().setText(text)); } } // 遍表格元素,类似处理段落元素 4. 输出结果 最后,我们需要将填充好的Word文档保存到磁盘上,可以使用XWPFDocument的write()方法将文档写入到OutputStream,然后保存到文件中。例如: doc.write(new FileOutputStream("output.docx")); 这样,我们就可以使用Java实现Word模板导出list了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值