springmvc實現excel文件導出


記一次springmvc實現excel文件導出,代碼直接復制簡單修改即可用。

第一步:excel pom依賴包

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

第二步:controller層

// 導出excel相關
@RequestMapping("/orderStaticExcel")
public void excelOrderStatic(@RequestBody FinanceReportsCommonRequest financeReportsCommonRequest, HttpServletResponse response) throws IOException {
    // 設置response參數,可以打開下載頁面
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + new String(("訂單統計" + ".xls").getBytes(), StandardCharsets.ISO_8859_1));
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new ByteArrayInputStream(omsReportStatisticsService.excelByte(financeReportsCommonRequest)));
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (IOException e) {
        logger.error("出現其他異常:", e);
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }
}

第三步:接口層

public interface OmsReportStatisticsService {
    byte[] excelByte(FinanceReportsCommonRequest financeReportsCommonRequest);
}

第四步:接口實現層

@Service("omsReportStatisticsServiceImpl")
public class OmsReportStatisticsServiceImpl implements OmsReportStatisticsService {
    private static final Logger logger = LoggerFactory.getLogger(OmsReportStatisticsServiceImpl.class);

    @Override
    public byte[] excelByte(FinanceReportsCommonRequest financeReportsCommonRequest) {
        ByteArrayOutputStream baos = null;
        try {
            // excel標題
            String[] title = {"訂單號", "客戶手機號", "支付日期", "實際支付日期", "期數", "應付租金", "已付租金", "應付增值費用","實付增值費用", "應付保險金額", "實付保險金額", "應付運費", "實付運費", "折扣金額", "實際折扣金額", "應付其他費用", "實付其他費用","應減免金額", "實際減免金額", "應付罰息", "實付罰息", "應付押金", "實付押金", "押金轉租金", "應付買斷費", "實付買斷費","用戶已支付(不包含押金)", "用戶已支付(包含押金)"};

            // 列的寬度
            int[] length = {
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20};

            // sheet名
            String sheetName = "訂單統計報表";

            String[][] content = null;

            PageInfo<OrderStaticReportResultDTO> pageInfo = this.orderFinanceStaticReport(financeReportsCommonRequest);
            content = new String[title.length][title.length];

            for (int i = 0; i < pageInfo.getList().size(); i++) {
                OrderStaticReportResultDTO repayBalance = pageInfo.getList().get(i);
                content[i][0] = repayBalance.getOrderNo();
                content[i][1] = repayBalance.getMobilePhoneNo();
                content[i][2] = repayBalance.getPayDate();
                content[i][3] = repayBalance.getFinishDate();
                content[i][4] = repayBalance.getCnt().toString();
                content[i][5] = repayBalance.getPayRentAmt().toString();
                content[i][6] = repayBalance.getActualPayRentAmt().toString();
                content[i][7] = repayBalance.getPayRaiseAmt().toString();
                content[i][8] = repayBalance.getActualPayRaiseAmt().toString();
                content[i][9] = repayBalance.getPayInsureAmt().toString();
                content[i][10] = repayBalance.getActualPayInsureAmt().toString();
                content[i][11] = repayBalance.getPayLogisticsAmt().toString();
                content[i][12] = repayBalance.getActualPayLogisticsAmt().toString();
                content[i][13] = repayBalance.getPayDiscountAmt().toString();
                content[i][14] = repayBalance.getActualPayDiscountAmt().toString();
                content[i][15] = repayBalance.getPayOtherAmt().toString();
                content[i][16] = repayBalance.getActualPayOtherAmt().toString();
                content[i][17] = repayBalance.getPayReductionAmt().toString();
                content[i][18] = repayBalance.getActualPayReductionAmt().toString();
                content[i][19] = repayBalance.getPayFineAmt().toString();
                content[i][20] = repayBalance.getActualPayFineAmt().toString();
                content[i][21] = repayBalance.getPayDepositAmt().toString();
                content[i][22] = repayBalance.getActualPayDepositAmt().toString();
                content[i][23] = repayBalance.getLimitDepositAmt().toString();
                content[i][24] = repayBalance.getBuyoutAmt().toString();
                content[i][25] = repayBalance.getActualBuyoutAmt().toString();
                content[i][26] = repayBalance.getCustActualExcludeDepositAmt().toString();
                content[i][27] = repayBalance.getCustActualIncludeDepositAmt().toString();
            }


            logger.info("to there !");

            // 創建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null, length);
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            logger.info("生成文件");
            baos.flush();
            //            return new ByteArrayInputStream(baos.toByteArray());
            return baos.toByteArray();
        } catch (Exception e) {
            logger.error("generateStreamByTrans err", e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    logger.error("close baos err", e);
                }
            }
        }
        return null;
    }
}    

第五、ExcelUtils工具類

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ExcelUtils {
    /**
     * 導出Excel
     *
     * @param sheetName sheet名稱
     * @param title     標題
     * @param values    內容
     * @param wb        HSSFWorkbook對象
     * @return HSSFWorkbook
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb, int[] length) {
        // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        // 創建一個居中格式
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 創建一個居中格式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        //聲明列對象
        HSSFCell cell = null;

        //創建標題
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(titleStyle);
            sheet.setColumnWidth(i, length[i] * 256);
        }
        if (values != null && values.length > 0) {
            //創建內容
            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.setCellValue(values[i][j]);
                    cell.setCellStyle(cellStyle);
                }
            }
        }
        return wb;
    }

    /**
     * 導出多個sheet的Excel表
     *
     * @param sheetNames sheet名稱
     * @param titles     標題
     * @param values     內容
     * @param wb         HSSFWorkbook對象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbookWithMoreSheet(List<String> sheetNames, List<String[]> titles, List<String[][]> values, HSSFWorkbook wb, List<int[]> lengths) {

        // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        for (int m = 0; m < sheetNames.size(); m++) {
            // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetNames.get(m));

            // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制
            HSSFRow row = sheet.createRow(0);

            HSSFRow englishRow = sheet.createRow(1);

            // 第四步,創建單元格,並設置值表頭 設置表頭居中
            HSSFCellStyle titleStyle = wb.createCellStyle();
            titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            titleStyle.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式

            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式

            //聲明列對象
            HSSFCell cell = null;

            int[] length = lengths.get(m);
            String[] title = titles.get(m);
            String[] englishTitle = titles.get(m + 2);

            //創建標題
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(titleStyle);
                sheet.setColumnWidth(i, length[i] * 256);
            }

            //創建標題
            for (int i = 0; i < englishTitle.length; i++) {
                cell = englishRow.createCell(i);
                cell.setCellValue(englishTitle[i]);
                cell.setCellStyle(titleStyle);
                sheet.setColumnWidth(i, length[i] * 256);
            }


            if (values != null) {
                String[][] value = values.get(m);
                //創建內容
                if (value != null && value.length > 0) {
                    for (int i = 0; i < value.length; i++) {
                        row = sheet.createRow(i + 2);
                        for (int j = 0; j < value[i].length; j++) {
                            //將內容按順序賦給對應的列對象
                            cell = row.createCell(j);
                            cell.setCellValue(value[i][j]);
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }
            }


        }
        return wb;
    }
    

    /**
     * @Author jason
     * @Description 發送響應流方法
     * @UpdateRemark: 修改內容
     * @Param [response, fileName]
     **/
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM