下载word报表

1.引入依赖

XML 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.5</version>
        </dependency>
        <!--&lt;!&ndash; Poi-tl Word 模板引擎&ndash;&gt;-->
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.12.2</version>
        </dependency>

2.示例代码

XML 复制代码
//动态表格策略类
public class ItemTablePolicy extends DynamicTableRenderPolicy {


    @Override
    public void render(XWPFTable table, Object data) throws Exception {

        if(data == null){

        return;
}    

Item item = JSON.parseObject(JSON.toJSONString(data),new TypeReference<>(){});
List<Subject> subjects = item.getSubject();
    int startRow = 1;

for(Subject subject : subjects ){
    XWPFTableRos insertNewTableRow = table.insertNewTableRow(startRow);
    for(int j = 0; j < 5; j++) insertNewTableRow.createCell();
    TableRenderPolicy.Helper.renderRow(table.getRow(startRow),Rows.of(
    Texts.of(subject.getSubjectId()).create(),
    Texts.of(subject.getName()).create(),
    Texts.of(subject.getSource()).create(),
    Texts.of(subject.getTeacherId()).create(),
    Texts.of(subject.getTeacherName()).create()).create());
    startRow++;
   
}
}
}

public void download(String id,HttpServletResponse) throws Exception{
    Item item = itemService.getItemById(id);
    if(null == item){
        throw new RuntimeException("该报告不存在!");
}

Map<String, Object> data = getDocData(item);

Configure configure = Configure.builder().bind("table",new ItemTablePolicy()).build();
File docxFile = new File(String.format("%s%s%s",Server.HOME_PATH, File.separator, "ItemReport.docx"));

//输出流生成导出的文件
String fileName = String.format("%s_%s_年度报告.docx",record.getName(),DateUtil.today());

File file = new File(fileName);

try{
    if(!docxFile.exists()){
    Resource resource = new ClassPathResource("/template/item.docx");
    org.apache.commons.io.FileUtils.copyToFile(resource.getInputStream(),file);

}

    XWPFTemplate.compile(docxFile.exists() ? docxFile : file, configure).render(data).writeToFile(file.getAbsolutePath());

//把文件写到response的输出流中 最后再删除两个中间文件
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8");

response.setHeader("Content-Length",String.valueOf(file.length()));
response.setHeader("Content-Disposition", String.format("attachment; filename=%s",URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName())));

exportFile(response, new FileInputStream(file));


    

}finally{

    file.delete();
}





}


public Map<String, Object> getDocData(Item record){

    Map<String,Object> data = new HashMap<>();
    data.put("title",Texts.of(String.format("%s年度报告",record.getName())).create());
    data.put("studentName",Texts.of(item.getName()).create());
    data.put("startTime",Texts.of(DateUtil.format(DateUtil.date(record.getStartTime()),"yyyy-MM-dd HH:mm:ss")).create());

data.put("endTime",Texts.of(DateUtil.format(DateUtil.date(record.getEndTime()),"yyyy-MM-dd HH:mm:ss")).create());

data.pue("totalNumber",Texts.of(record.getTotalNumber()).create());


ChartSingleSeriesRenderData pie = Charts
    .ofSingleSeries("及格情况",new String[]{"及格数量","不及格数量"})
    .series("countries",new Integer[]{ record.getTotal() - record.getAbnormal(), record.getAbnormal()})
    .create();

    data.put("pieChart",pie);

return data;



}



public static void exportFile(HttpServletResponse response, InputStream is){
 
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
try{
os = response.getOutputStream();
bis = new BufferedInputStream(is);
int i = bis.read(buff);
while(i!=-1){
    os.write(buff, 0, buff.length);
    os.flush();
    i = bis.read(buff);
 
 
}
 
 
}catch (IOException e){
 
    e.printStackTrace();
}finally {
 
    if(null != bis){
    try{
        bis.close();
 
}catch (IOException e){
    e.printStackTrace();
}
 
}
 
if( os != null){
 
    try{
        os.close();
 
}catch (IOException e ){
  e.printStackTrace();
}
 
}
 
}
 
 
}
相关推荐
荔枝吻12 分钟前
【抽丝剥茧知识讲解】引入mybtis-plus后,mapper实现方式
java·sql·mybatis
在未来等你17 分钟前
互联网大厂Java求职面试:构建高并发直播平台的架构设计与优化
java·spring boot·微服务·kubernetes·高并发·分布式系统·直播平台
轮到我狗叫了41 分钟前
力扣.1471数组的k个最强值,力扣.1471数组的k个最强值力扣1576.替换所有的问号力扣1419.数青蛙编辑力扣300.最长递增子序列
java·数据结构·算法
秋野酱1 小时前
基于SpringBoot的家政服务系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端
趁你还年轻_1 小时前
常用的Java工具库
java
不再幻想,脚踏实地1 小时前
Spring Boot 日志
java·spring boot·后端
小小Ruby1 小时前
利用vba替换word中多个表格,相邻单元格的文字
word
风象南2 小时前
SpringBoot中10种动态修改配置的方法
java·spring boot·后端
金斗潼关2 小时前
基于OAuth2+SpringSecurity+Jwt实现身份认证和权限管理后端服务
java·鉴权
代码小将5 小时前
Leetcode209做题笔记
java·笔记·算法