poi实现数据导出成xlsx

 在工作中有遇到导出文件的功能要实现,直接贴代码


public void exportData(HttpServletResponse response) {
    ServletOutputStream outputStream = null;
    FileInputStream fileInputStream = null;
    File temp = null;
    JSONArray jsonArray=new JSONArray();//把数据放在jsonArray中
    List<String> list=new ArrayList<>();
    list.add("第一行");
    list.add("第二行");
    list.add("第三行");
    list.stream().forEach(s -> {
       JSONObject jsonObject=new JSONObject();
       jsonObject.put("data",s);
        jsonArray.add(jsonObject);
    });
    Map<String, String> headMap = new LinkedHashMap<>();// 存放表头部信息 必须是 LinkedHashMap
    headMap.put("data","数据");//需要对应
    // 生成文件临时存放目录
    String tempFiles = System.getProperty("java.io.tmpdir") + "/";
    String title = "信息数据明细.xlsx";
    temp = new File(tempFiles, title);
    if (!temp.getParentFile().exists()) {
        temp.getParentFile().mkdirs();
    }
    try {
        OutputStream outXlsx = new FileOutputStream(tempFiles + title);
        exportToExcel(headMap, jsonArray, null, 0, outXlsx);
        outXlsx.close();
        //设置请求头
        response.setHeader("content-type", "text/plain");
        response.setHeader("content-type", "application/x-msdownload;");
        response.setContentType("text/plain; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String((title).getBytes(), StandardCharsets.ISO_8859_1));
        outputStream = response.getOutputStream();
        fileInputStream = new FileInputStream(tempFiles + title);
        byte[] bytes = new byte[1024];
        int size;
        while (-1 != (size = fileInputStream.read(bytes))) {
            outputStream.write(bytes, 0, size);
        }
        outputStream.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static void exportToExcel(Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
    if(datePattern==null) datePattern = "yyyy-MM-dd HH:mm:ss";
    // 声明一个工作薄
    SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存
    //设置单元格风格,居中对齐. 垂直对齐
    CellStyle cs = workbook.createCellStyle();
    cs.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    cs.setVerticalAlignment(VerticalAlignment.DISTRIBUTED);
    // 生成一个表格
    SXSSFSheet sheet = workbook.createSheet();
    //设置列宽
    int minBytes = colWidth<50?50:colWidth;//至少字节数
    int[] arrColWidth = new int[headMap.size()];
    // 产生表格标题行,以及设置列宽
    String[] properties = new String[headMap.size()];
    String[] headers = new String[headMap.size()];
    int ii = 0;
    for (Iterator<String> iter = headMap.keySet().iterator(); iter
            .hasNext();) {
        String fieldName = iter.next();
        properties[ii] = fieldName;
        headers[ii] = headMap.get(fieldName);
        int bytes = fieldName.getBytes().length;
        arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;
        sheet.setColumnWidth(ii,arrColWidth[ii]*1024);
        ii++;
    }
    // 遍历集合数据,产生数据行
    int rowIndex = 0;
    for (Object obj : jsonArray) {
        if(rowIndex == 65535 || rowIndex == 0){
            if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
            SXSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =1
            for(int i=0;i<headers.length;i++)
            {  SXSSFCell newCell = headerRow.createCell(i);
                newCell.setCellValue(headers[i]);
                newCell.setCellStyle(cs);
            }
            rowIndex = 1;//数据内容从 rowIndex=1开始
        }
        JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
        SXSSFRow dataRow = sheet.createRow(rowIndex);
        for (int i = 0; i < properties.length; i++)
        {
            SXSSFCell newCell = dataRow.createCell(i);

            Object o =  jo.get(properties[i]);
            String cellValue = "";
            if(o==null) cellValue = "";
            else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);
            else if(o instanceof Float || o instanceof Double)
                cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            else cellValue = o.toString();

            newCell.setCellValue(cellValue);
            newCell.setCellStyle(cs);
        }
        rowIndex++;
    }
    // 自动调整宽度 并且调整默认单元格长度为6个中文字符
    sheet.trackAllColumnsForAutoSizing();
    for (int i =0; i < headers.length; i++) {
        sheet.autoSizeColumn(i);
        int width = Math.max(15 * 256, Math.min(255 * 256, sheet.getColumnWidth(i) * 12 / 10));
        sheet.setColumnWidth(i, width);
    }
    try {
        workbook.write(out);//将工作簿写入outPutStream
        workbook.close();
        boolean flag =  workbook.dispose();//释放磁盘空间。处理在磁盘上支持这个工作簿的临时文件。调用该方法将使工作簿不可用。
        System.out.println(flag);//如果所有临时文件都被成功删除,则为真。
    } catch (IOException e) {
        e.printStackTrace();
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值