Java 使用 poi 导出Excel 源码完整示例

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


    /**
     * 导出商品集下的商品
     *
     * @param itemsetId
     */
    @GetMapping("/export.json")
    @OvsExceptionHandler
    public void export(@RequestParam("itemsetId") Long itemsetId, HttpServletResponse response) throws Exception {
        List<ItemsetItemDTO> list = new ArrayList<>();

        ItemsetItemQuery q = new ItemsetItemQuery();
        q.setItemsetId(itemsetId);
        q.setCurrentPage(1);
        q.setPageSize(500);

        PageResult<ItemsetItemDTO> pageResult = itemsetService.getItemList(q);

        while (!CollectionUtils.isEmpty(pageResult.getList())) {
            // 最多导出10w条
            if (list.size() > 100000) {
                break;
            }

            list.addAll(pageResult.getList());

            // next page
            q.setCurrentPage(q.getCurrentPage() + 1);
            pageResult = itemsetService.getItemList(q);
        }

        OutputStream outputStream = null;
        try {
            HSSFWorkbook workbook = exportExcel(list);
            outputStream = response.getOutputStream();
            response.reset();
            response.setContentType("application/msexcel");
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //设置浏览器响应头对应的Content-disposition 解决中文名字乱码
            String filename = "选品集商品列表_" + System.currentTimeMillis();
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xls");
            workbook.write(outputStream);
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    public HSSFWorkbook exportExcel(List<ItemsetItemDTO> list) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        try {
            HSSFSheet sheet = workbook.createSheet("选品集商品列表");
            Row row = sheet.createRow(0);
            // excle标题
            String[] header = new String[]{"商品ID", "商品名称", "类目", "供应商ID", "货源渠道", "供货价"};
            for (int i = 0; i < header.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(header[i]);
                sheet.setColumnWidth(i, header[i].getBytes().length * 350);
            }
            //excel 内容
            for (int s = 0; s < list.size(); s++) {
                ItemsetItemDTO info = list.get(s);
                row = sheet.createRow(s + 1);
                row.createCell(0).setCellValue(info.getItemId());
                row.createCell(1).setCellValue(info.getItemName());
                row.createCell(2).setCellValue(info.getPcateLeafName());
                row.createCell(3).setCellValue(info.getSrcSellerId());
                row.createCell(4).setCellValue(info.getBizType());
                row.createCell(5).setCellValue(info.getTwMinPrice().toString());
            }
        } catch (Exception e) {
            log.error("exportExcel:", e);
        }
        return workbook;
    }

其中,pom.xml 依赖为:

        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-scratchpadartifactId>
            <version>3.15version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.15version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.15version>
        dependency>

你可能感兴趣的:(Java)