java使用poi,导出数据致word模板,以提供下载。

首先制定word模板,改成你需要的样子。格式如下,$需要变量名称$。使用poi。

从前台传值过来:window.location.href = basePath + '**.do?id='+encodeURI(encodeURI(id, "UTF-8"),"UTF-8");

    //获取模板文件的目录地址
        String path = request.getSession().getServletContext().getRealPath("/");
        String fileDir = new File(path+"jsp/templet/").getCanonicalPath();

    //获取模板文件
        File demoFile=new File(fileDir + "/doc.doc");

    FileInputStream in = new FileInputStream(demoFile);
        HWPFDocument hdt = new HWPFDocument(in);
        //替换读取到的word模板内容的指定字段
        Range range = hdt.getRange();
        Map<String, String> map = new HashMap<String, String>();
        map.put("$BIANMA$", SSCID);
        map.put("$DENAME$", DNAME);
        map.put("$DATE$", now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1)+"月"+now.get(Calendar.DAY_OF_MONTH)+"日");
        for (Map.Entry<String,String> entry:map.entrySet()) {
            range.replaceText(entry.getKey(),entry.getValue());
        }
        
        //输出word内容文件流,提供下载
        response.setContentType("application/x-msdownload");
        String name = java.net.URLEncoder.encode(DNAME+".doc", "UTF8");
        name = new String((name).getBytes("UTF-8"), "ISO-8859-1");
        response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+name);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        ServletOutputStream servletOS = response.getOutputStream();
        hdt.write(ostream);
        servletOS.write(ostream.toByteArray());
        servletOS.flush();
        servletOS.close();

Java中,利用POI-TL(Apache POI的Template Library)模板引擎来处理Word文档并嵌入多重循环是很常见的需求。POI-TL提供了一种方便的方式来操作Microsoft Office文件,包括Word。下面是一个基本步骤,展示如何在模板中添加多重循环: 1. **引入依赖**: 首先,你需要在项目中引入`org.apache.poi.xwpf.usermodel`和`org.apache.poi.xwpf.template`库,这两个包包含处理Word模板和文档的功能。 2. **创建模板**: 使用`XWPFDocument.create()`方法创建一个新的Word模板文档,并加载预定义的模板文件。你可以从本地读取模板文件,或者直接作为字符串内容传递。 ```java XWPFDocument template = new XWPFDocument(new FileInputStream("template.docx")); ``` 3. **设置循环变量**: 设定一个或多个需要迭代的数据集合,比如List、Map等,用于填充模板中的循环部分。例如,假设你有一个学生列表: ```java List<Student> students = ...; // 学生对象列表 ``` 4. **遍历并插入数据**: 使用`XWPFParagraph`的`addRun()`方法,在模板的每个循环位置插入新的文本行。对于每个学生,你可以创建一个新的段落或者追加到现有段落。 ```java for (Student student : students) { XWPFParagraph para = template.addNewParagraph(); para.addRun().append(student.getName()); // 如果有其他信息,如成绩,可以继续添加到run中 } ``` 5. **替换占位符**: 在模板中可能有一些特殊的标签(通常是特殊字符或标记),表示需要动态填充的部分。使用`XWPFTextRun.replaceText()`方法将这些占位符替换为实际数据。 6. **保存结果**: 最后,将修改后的模板保存为一个新的Word文档。 ```java OutputStream outputStream = new FileOutputStream("output.docx"); template.write(outputStream); outputStream.close(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值