Poi 导出excel多个sheet的内容

Poi 导出excel多个sheet的内容

目录

Poi 导出excel多个sheet的内容

代码:

Contrller

Service:

导出引用:ExcelExportUtil

导出类:PoiMulExcelExporter

测试用postman:

结果:

总结:


 

学习了导出简单表头单个sheet内容,多个sheet的内容处理就简单多了。思路还是一样的,不过这边代码有些变化。

 

代码:

Contrller

@RestController
@RequestMapping("/excel")
@Slf4j
public class ExcelController {
    @Resource
    private ExcelService excelService;

    @GetMapping("/exportMulData")
    @ApiOperation(value="导出多个sheet数据接口")
    public void exportMulData(HttpServletResponse response) {
        excelService.exportMulData(response);
    }

    @GetMapping("/exportSingleDatas")
    @ApiOperation(value="导出单个数据接口")
    public void exportSingleDatas(HttpServletResponse response) {
        excelService.exportSingleDatas(response);
    }

}

 

Service:

@Service
public class ExcelService {

    public void exportSingleDatas(HttpServletResponse response) {
        String tableName = "order single " + LocalDate.now().getYear() + "-" + LocalDate.now().getMonthValue() + "-"
                + LocalDate.now().getDayOfMonth();
        // 获取需要导出的数据
        List> dataList = getResultData();
        // 需要展示的列
        List fieldList = Lists.newArrayList("orderTime","total","except","overTime","successRate");
        // 匹配数据
        List> results = matchFieldData(dataList, fieldList);
        // 设置表题
        String[] titleList = {"日期","订单总量","异常量","超时量","成功率"};
        try {
            ExcelExportUtil.exportExcel(tableName, titleList, results,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportMulData(HttpServletResponse response) {
        String tableName = "order mul sheet " + LocalDate.now().getYear() + "-" + LocalDate.now().getMonthValue() + "-"
                + LocalDate.now().getDayOfMonth();
        // 获取需要导出的数据
        List> dataList = getResultData();
        List titleList = new ArrayList<>();
        List>> contentList = new ArrayList<>();
        // 需要展示的列
        List fieldList1 = Lists.newArrayList("orderTime","total","except","overTime","successRate");
        List fieldList2 = Lists.newArrayList("orderTime","total","except","timelyRate","successRate");
        // 匹配数据
        List> results1 = matchFieldData(dataList, fieldList1);
        List> results2 = matchFieldData(dataList, fieldList2);
        contentList.add(results1);
        contentList.add(results2);
        // 设置表题
        String[] title1 = {"日期","订单总量","异常量","超时量","成功率"};
        String[] title2 = {"日期","订单总量","异常量","及时率","成功率"};
        titleList.add(title1);
        titleList.add(title2);
        try {
            ExcelExportUtil.exportExcel(tableName, titleList, contentList,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private List> getResultData(){

        String data = "[{\"orderTime\":\"2021-03-03 10:10:10\",\"total\":55,\"except\":12,\"overTime\":8,\"timelyRate\":\"88%\",\"successRate\":\"77%\"},{\"orderTime\":\"2021-03-03 10:15:10\",\"total\":155,\"except\":44,\"overTime\":20,\"timelyRate\":\"78%\",\"successRate\":\"65%\"},{\"orderTime\":\"2021-03-03 10:20:10\",\"total\":85,\"except\":6,\"overTime\":5,\"timelyRate\":\"98%\",\"successRate\":\"97%\"}]";

        return GsonUtils.changeJsonToList(data);

    }

    private List> matchFieldData(List> dataList, List fieldList) {
        return ListUtils
                .emptyIfNull(dataList).stream().filter(Objects::nonNull).map(e -> ListUtils.emptyIfNull(fieldList)
                        .stream().map(f -> MapUtils.getString(e, f)).collect(Collectors.toList()))
                .collect(Collectors.toList());
    }

}

GsonUtils 引用 看字符串转化为list

 

导出引用:ExcelExportUtil

@Component
public class ExcelExportUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(ExcelExportUtil.class);

   
    public static void exportExcel(String fileName, String[] titles, List> result,
                                         HttpServletResponse response) {
        List titleList = Lists.newArrayList();
        List>> contentList = Lists.newArrayList();
        titleList.add(titles);
        contentList.add(result);
        exportExcel(fileName, titleList, contentList, response);
    }

    public static void exportExcel(String fileName, List titleList, List>> result,
            HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            new PoiMulExcelExporter().export(response, fileName, changeStrArrToList(titleList), result);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
}

这边修改了title的类型,本想用List的,都是List类型,会导致方法名会重复,改成String[]类型就可以。后面就直接调用同一个方法名,根据参数不同去判断选择

Poi 导出excel多个sheet的内容_第1张图片

 

导出类:PoiMulExcelExporter

public class PoiMulExcelExporter {

    PoiMulExcelExporter() {}

    /*多个sheet页*/
    public void export(HttpServletResponse response, String fileName, List> titleList,
                       List>> contentList) {
        HSSFSheet sheet;
        try (HSSFWorkbook workbook = new HSSFWorkbook(); OutputStream output = response.getOutputStream()) {
            setResponse(response, fileName);
            int sheetNum = titleList.size();
            for (int i = 0; i < sheetNum; i++) {
                sheet = workbook.createSheet("Sheet" + (i + 1));
                int rowNum = 0;
                createHeader(workbook, sheet, titleList.get(i), rowNum);
                rowNum++;
                createContent(sheet, contentList.get(i), rowNum);
            }
            workbook.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void createHeader(HSSFWorkbook workbook, HSSFSheet sheet, List titles, int rowNum) {
        setHeaderStyle(workbook);
        setSheetContent(sheet, titles, rowNum);
    }


    private static void setSheetContent(HSSFSheet sheet, List contentList, int rownum) {
        HSSFRow row = sheet.createRow(rownum);
        AtomicInteger i = new AtomicInteger();
        for (String title : ListUtils.emptyIfNull(contentList)) {
            if (!StringUtils.isEmpty(title)) {
                HSSFCell cell = row.createCell(i.getAndIncrement());
                cell.setCellValue(title);
            }
        }
    }

    private void createContent(HSSFSheet sheet, List> content, int rownum) throws Exception {
        for (List lineData : content) {
            setSheetContent(sheet,lineData,rownum);
            rownum++;
        }
    }

    private void setResponse(HttpServletResponse response, String fileName) {
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", getResponseHeader(fileName));
    }

    private String getResponseHeader(String fileName) {
        return "attachment; filename=" + gbToUtf8(fileName) + ".xls";
    }

    private static String gbToUtf8(String src) {
        byte[] b = src.getBytes();
        char[] c = new char[b.length];
        for (int x = 0; x < b.length; x++) {
            c[x] = (char) (b[x] & 0x00FF);
        }
        return new String(c);
    }

    private static void setHeaderStyle(HSSFWorkbook workbook) {
        CellStyle style = workbook.createCellStyle();//设置样式
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 13);//设置字体大小
        font.setBold(true);//字体加粗
        style.setFont(font);//设置的字体
        style.setBorderTop(BorderStyle.DASHED);//上边框
        style.setBorderBottom(BorderStyle.DASHED); //下边框
        style.setBorderBottom(BorderStyle.DASHED);//左边框
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());//右边框颜色
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());//上边框颜色
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //下边框颜色
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); //左边框颜色
        style.setBorderBottom(BorderStyle.DASHED);//右边框
        style.setAlignment(HorizontalAlignment.LEFT);//设置水平对齐的样式为居中对齐
        style.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直对齐的样式为居中对齐
    }

}

 

测试用postman:

 

结果:

Poi 导出excel多个sheet的内容_第2张图片

Poi 导出excel多个sheet的内容_第3张图片

 

 

总结:

    多个sheet的内容处理,主体还是按单个sheet的内容去处理,然后逐个遍历。单个sheet的内容,把数据拼接成多个的去处理。

 

你可能感兴趣的:(工具,poi,excel,多个sheet,导出excel)