Java 導出 Excel

1.公用工具類

  /**
     * 導出
     *
     * @param sheetName
     * @param titleName
     * @param fileName
     * @param columnNumber
     * @param columnWidth
     * @param columnName
     * @param dataList
     * @param response
     * @throws Exception
     */
    public static void exportWithResponse(String sheetName, String titleName,
                                          String fileName, int columnNumber, int[] columnWidth,
                                          String[] columnName, String[][] dataList,
                                          HttpServletResponse response) throws Exception {
        log.info("columnNumber:{}" , columnName.length);
        log.info("columnWidth.length:{}" , columnWidth.length);
        log.info("columnName.length:{}"  , columnName.length);
        if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
            // 第一步,創建一個webbook,對應一個Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
            // sheet.setDefaultColumnWidth(15); //統一設置列寬
            for (int i = 0; i < columnNumber; i++) {
                for (int j = 0; j <= i; j++) {
                    if (i == j) {
                        sheet.setColumnWidth(i, columnWidth[j] * 256); // 單獨設置每列的寬
                    }
                }
            }
            // 創建第0行 也就是標題
            HSSFRow row1 = sheet.createRow((int) 0);
            row1.setHeightInPoints(50);// 設備標題的高度
            // 第三步創建標題的單元格樣式style2以及字體樣式headerFont1
            HSSFCellStyle style2 = wb.createCellStyle();
            style2.setAlignment(HorizontalAlignment.CENTER);
            style2.setVerticalAlignment(VerticalAlignment.CENTER);
            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);

            HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 創建字體樣式
            //headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體加粗
            headerFont1.setFontName("黑體"); // 設置字體類型
            headerFont1.setFontHeightInPoints((short) 15); // 設置字體大小
            style2.setFont(headerFont1); // 爲標題樣式設置字體樣式

            HSSFCell cell1 = row1.createCell(0);// 創建標題第一列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
                    columnNumber - 1)); // 合併列標題
            cell1.setCellValue(titleName); // 設置值標題
            cell1.setCellStyle(style2); // 設置標題樣式

            // 創建第1行 也就是表頭
            HSSFRow row = sheet.createRow((int) 1);
            row.setHeightInPoints(37);// 設置表頭高度

            // 第四步,創建表頭單元格樣式 以及表頭的字體樣式
            HSSFCellStyle style = wb.createCellStyle();
            style.setWrapText(true);// 設置自動換行


            style.setBottomBorderColor(HSSFColor.BLACK.index);


            HSSFFont headerFont = (HSSFFont) wb.createFont(); // 創建字體樣式

            headerFont.setFontName("黑體"); // 設置字體類型
            headerFont.setFontHeightInPoints((short) 10); // 設置字體大小
            style.setFont(headerFont); // 爲標題樣式設置字體樣式

            // 第四.一步,創建表頭的列
            for (int i = 0; i < columnNumber; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(columnName[i]);
                cell.setCellStyle(style);
            }

            // 第五步,創建單元格,並設置值
            for (int i = 0; i < dataList.length; i++) {
                row = sheet.createRow((int) i + 2);
                // 爲數據內容設置特點新單元格樣式1 自動換行 上下居中
                //   HSSFCellStyle zidonghuanhang = wb.createCellStyle();
                //  zidonghuanhang.setWrapText(true);// 設置自動換行


                // 爲數據內容設置特點新單元格樣式2 自動換行 上下居中左右也居中
                //    HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
                //    zidonghuanhang2.setWrapText(true);// 設置自動換行

                // 設置邊框

                HSSFCell datacell = null;
                for (int j = 0; j < columnNumber; j++) {
                    datacell = row.createCell(j);
                    datacell.setCellValue(dataList[i][j]);
                    //   datacell.setCellStyle(zidonghuanhang2);
                }
            }

            // 第六步,將文件存到瀏覽器設置的下載位置
            String filename = fileName + ".xls";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
            OutputStream out = response.getOutputStream();
            try {
                wb.write(out);// 將數據寫出去
                String str = "導出" + fileName + "成功!";
                log.info(str);
            } catch (Exception e) {
                e.printStackTrace();
                String str1 = "導出" + fileName + "失敗!";
                log.info(str1);
            } finally {
                out.close();
            }

        } else {
            log.info("列數目長度名稱三個數組長度要一致");
        }

    }

2.調用

  /**
     * 訂單列表導出
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toExcel", produces = "application/json;charset=utf-8")
    @ResponseBody
    public void toExcel(HttpServletRequest request, HttpServletResponse response) {

			//查詢 
			List<OrderModel> orderModels = orderService.getPageList(orderRequest);
			
			 String sheetName = "訂單";
        String titleName = "訂單導出";
        String fileName = "訂單導出" + CommonTool.getDateTime();
        int[] columnWidth = {20, 20, 20};
        String[] columnName = {"訂單號", "內部訂單號", "備註"
        };
        String[][] dataList = new String[orderDTOS.size()][columnName.length];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int columnNumber = columnName.length;
		 try {
            for (int i = 0; i < orderDTOS.size(); i++) {
                dataList[i][0] = orderDTOS.get(i).getOrderModel().getNumber();
                dataList[i][1] = orderDTOS.get(i).getOrderModel().getUnionOrderNumber();
                dataList[i][2] = orderDTOS.get(i).getOrderModel().getRemark();

                if (orderDTOS.get(i).getOrderModel().getState() == OrderConst.ORDER_STATE_CANCELLED) {
                    dataList[i][3] = "已取消";
                } else if (orderDTOS.get(i).getOrderModel().getState() == OrderConst.ORDER_STATE_COMPLETED) {
                    dataList[i][3] = "已完成";
                } else if (orderDTOS.get(i).getOrderModel().getState() == OrderConst.ORDER_STATE_TO_BE_CONFIRMED) {
                    if (orderDTOS.get(i).getOrderModel().getDriverUid() == 0) {
                        dataList[i][3] = "已發佈";
                    } else {
                        dataList[i][3] = "待確認協議";
                    }

                } else if (orderDTOS.get(i).getOrderModel().getState() == OrderConst.ORDER_STATE_TO_CONFIRM_RECEIPT) {
                    dataList[i][3] = "待簽收";
                } else {
                    dataList[i][3] = "運輸中";
                }
 }
            CommonTool.exportWithResponse(sheetName, titleName, fileName,
                    columnNumber, columnWidth, columnName, dataList, response);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章