POI导入导出Excel,

1.导入pom

 <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.9</version>
    </dependency>

2.导出工具类
package com.ujiuye.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.;
import java.util.
;

@Component
public class ExcelUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtils.class);

private static ExcelUtils excelUtils;



@SuppressWarnings("unchecked")
public static void export(String[][] columnNames,
                          List<?> listData, String fileName, HttpServletResponse response) {

    JSONArray arr = JSONArray.parseArray(JSON.toJSONString(listData));

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, Object> map0 = new HashMap<String, Object>();
    map0.put("sheetName", "sheet1");
    list.add(map0);
    for (int i = 0; i < arr.size(); i++) {
        JSONObject obj = arr.getJSONObject(i);
        Map<String, Object> map = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(JSON.parseObject(JSON.toJSONString(obj), listData.get(0).getClass())), Map.class);
        list.add(map);
    }

    try {
        fileName = fileName + ".xls";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ExportToExcelUtil.createWorkBook(list, columnNames).write(baos);
        byte[] content = baos.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        ServletOutputStream sos = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(sos);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error("导出excel异常:{}", e.getMessage());
    }
}

}
3.controller

 @RequestMapping("downExcel")
    public void downExcel(HttpServletResponse response){
        List<Task> list = taskService.showAllTask("5");
        String [] []str = {
            {"id","task的ID"},
            {"starttime","起始时间"},
            {"endtime","结束时间"},
            {"level","等级"},
            {"remark","描述"}
        };
        ExcelUtils.export(str,list,"taskInfo",response);
    }

4.service层
注:StatusDto类只封装了一个status属性

@Override
    public List<Task> showAllTask(String status) {
        StatusDto statusDto = new StatusDto();
        statusDto.setStatus(Integer.parseInt(status));
        return taskMapper.selectAllTask(statusDto);
    }

5.mapper

<select id="selectAllTask" parameterType="com.ujiuye.usual.bean.Dto.StatusDto" resultMap="BaseResultMap_Task">
    select
    <include refid="Base_Column_List"/>
    from task
    <where>
      <if test="status == 1">
        and status = 1
      </if>
      <if test="status == 2">
        and status = 2
      </if>
      <if test="status == 3">
        and status = 3
      </if>

    </where>
  </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值