ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

poi实现数据导出成xlsx

2021-05-19 16:33:49  阅读:262  来源: 互联网

标签:xlsx headMap sheet String int 导出 rowIndex poi new


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


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();
    }
}

标签:xlsx,headMap,sheet,String,int,导出,rowIndex,poi,new
来源: https://blog.csdn.net/gfdedexdcf/article/details/117033895

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有