工具类Excel导出那些事儿

Posted Summer-Zheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工具类Excel导出那些事儿相关的知识,希望对你有一定的参考价值。

      Excel的导出需求层出不穷,,之前都是直接导出list<T>,或者导出List<map>,现在需要导出双标题Excel。使用poi实现.本篇先介绍基础的导出方法

引用的jar包

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

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-excelant</artifactId>
    <version>3.17</version>
</dependency>

首先是基础用法(单表头导出)

//要导出的数据
List<T> list;
String[] tempTitle = "第一列","第二列","第三列","第四列";
List<String> tempList= Arrays.asList(tempTitle);
List<String> titleList = new ArrayList<>();
titleList.addAll(tempList);
//动态字段
List<String> collectTitle = list.get(0).getList().stream().map(ResultVo::getName).collect(Collectors.toList());
List<String> titleTempList = new ArrayList<>();
collectTitle.forEach(item -> 
    titleTempList.add("返回字段(" + item + ")");
);
titleList.addAll(titleTempList);
String[] title = titleList.toArray(new String[]);

String fileName = "数据导出_"  + DateUtils.formatDate(new Date()) + ".xlsx";
String sheetName = "Sheet明细";

try 
    String[][] content = new String[list.size()][];
    for (int i = 0; i < list.size(); i++) 
        content[i] = new String[title.length];
        DownExcelVo dto = list.get(i);
        //第一列
        content[i][0] = dto.getNo();
        //第二列
        content[i][1] = (dto.getIsSuccess().equals(1) ? "成功" :"失败");
        //第三列
        content[i][2] = String.valueOf(dto.getTime());
        //第四列
        content[i][3] = (dto.getCreateTime() != null) ? DateUtils.formatDate(dto.getCreateTime()) : "";
        //动态字段列
        List<ResultVo> dictList = dto.getList();
        if(CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(dictList))
            for(int j = 0;j < dictList.size();j++)
                ResultVo resultVo = dictList.get(j);
                content[i][j + 4] = resultVo.getValue() + "," + (resultVo.getValueStatus().equals(1) ? "正常值" :"异常值");
            
        

    
    ExcelUtils.export(response, fileName, sheetName, title, content);
 catch (Exception ex) 
    logger.error("导出数据失败", ex);
    throw new RuntimeException(CodeMsgEnum.SYSTEM_PUBLIC_ERROR_APPKEY.getCode());

工具类方法如下:

public static void export(HttpServletResponse response, String fileName, String sheetName, String[] title, String[][] content) 
    XSSFWorkbook wb = new XSSFWorkbook();
    OutputStream os = null;
    try 
        wb = exportXls(sheetName, title, content, wb);
        setResponse(response, fileName);
        os = response.getOutputStream();
        wb.write(os);
        os.flush();
     catch (Exception e) 
        LOGGER.error("io error");
     finally 
        try 
            wb.close();
            if (os != null) 
                os.close();
            
         catch (Exception e) 
            LOGGER.error("close io error");
        
    


/**
 * 发送响应流方法
 */
public static void setResponse(HttpServletResponse response, String fileName) 
    try 
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);


        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
     catch (Exception ex) 
        LOGGER.info("error response head");
    


/**
 * 导出Excel
 *
 * @param sheetName sheet名称
 * @param title     标题
 * @param values    内容
 * @param wb        HSSFWorkbook对象
 * @return
 */
public static XSSFWorkbook exportXls(String sheetName, String[] title, String[][] values, XSSFWorkbook wb) 

    // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
    if (wb == null) 
        wb = new XSSFWorkbook();
    

    // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
    XSSFSheet sheet = wb.createSheet(sheetName);

    // 第四步,创建单元格,并设置值表头 设置表头居中
    XSSFCellStyle style = wb.createCellStyle();
    // 创建一个居中格式
    style.setAlignment(HorizontalAlignment.CENTER);


    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell;
    //创建标题
    for (int i = 0; i < title.length; i++) 
        cell = row.createCell(i);
        cell.setCellValue(title[i]);
        cell.setCellStyle(style);
    

    //创建内容
    for (int i = 0; i < values.length; i++) 
        row = sheet.createRow(i + 1);
        for (int j = 0; j < values[i].length; j++) 
            //将内容按顺序赋给对应的列对象
            cell = row.createCell(j);
            cell.setCellStyle(style);
            cell.setCellValue(values[i][j]);
        
    
    return wb;

 

以上是关于工具类Excel导出那些事儿的主要内容,如果未能解决你的问题,请参考以下文章

工具类Excel导出那些事儿

工具类Excel导出那些事儿

工具类Excel导出那些事儿

【springboot+easypoi】一行代码搞定excel导入导出

Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

工作中最常用的Excel函数公式大全