Jenke 使用apache的poi實現導入導出excel

1、jar包:poi-3.14-20160307.jar、poi-ooxml-3.14-20160307.jar

2、導入(本例實現瞭解析excel生成List):

@Override
    public Map<String, Object> parseExcel(String fileName) {

        // 1.準備返回的變量
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String message = "success";
        List<Stone> stones = new ArrayList<Stone>();

        boolean isE2007 = false; // 判斷是否是excel2007格式
        if (fileName.endsWith("xlsx")) {
            isE2007 = true;
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

        // 2.準備workbook
        // 同時支持Excel 2003、2007
        File excelFile = new File(fileName); // 創建文件對象
        Workbook workbook = null;
        // 根據文件格式(2003或者2007)來初始化
        try {
            FileInputStream is = new FileInputStream(excelFile); // 文件流
            if (isE2007) {
                workbook = new XSSFWorkbook(is);
            } else {
                workbook = new HSSFWorkbook(is);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3.遍歷集合,組裝結果
        int sheetCount = workbook.getNumberOfSheets(); // Sheet的數量
        // 遍歷每個Sheet
        for (int s = 0; s < sheetCount; s++) {
            Sheet sheet = workbook.getSheetAt(s);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 獲取總行數
            // 遍歷每一行
            for (int r = 1; r < rowCount; r++) {
                Stone stone = new Stone();
                Row row = sheet.getRow(r);
                int cellCount = row.getPhysicalNumberOfCells(); // 獲取總列數
                // 遍歷每一列
                for (int c = 0; c < cellCount; c++) {
                    Cell cell = row.getCell(c);
                    int cellType = cell.getCellType();
                    String cellStringValue = null;
                    switch (cellType) {
                    case Cell.CELL_TYPE_STRING: // 文本
                        cellStringValue = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC: // 數字、日期
                        if (DateUtil.isCellDateFormatted(cell)) {
                            cellStringValue = fmt.format(cell.getDateCellValue()); // 日期型
                        } else {
                            cellStringValue = String.valueOf(cell.getNumericCellValue()); // 數字
                            if (cellStringValue.contains("E")) {
                                cellStringValue = String.valueOf(new Double(cell.getNumericCellValue()).longValue()); // 數字
                            }
                        }
                        break;
                    case Cell.CELL_TYPE_BOOLEAN: // 布爾型
                        cellStringValue = String.valueOf(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_BLANK: // 空白
                        cellStringValue = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_ERROR: // 錯誤
                        cellStringValue = "錯誤";
                        break;
                    case Cell.CELL_TYPE_FORMULA: // 公式
                        cellStringValue = "錯誤";
                        break;
                    default:
                        cellStringValue = "錯誤";
                    }

                    if (cellStringValue.equals("錯誤")) {
                        message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第[" + (c + 1)
                                + "]列解析錯誤";
                        resultMap.put("message", message);
                        return resultMap;
                    }

                    cellStringValue = cellStringValue.trim();

                    switch (c) {
                    case ConstantsUtil.STONE_EXCEL_COLUMN_STONEID:
                        try {
                            new Long(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setStoneId(new Long(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_SHAPE:
                        stone.setShape(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_CARAT:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setCarat(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_COLOUR:
                        stone.setColour(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_CLARITY:
                        stone.setClarity(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_CUT:
                        stone.setCut(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_POLISH:
                        stone.setPolish(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_SYM:
                        stone.setSym(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_FLUOR:
                        stone.setFluor(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_DIAMETER:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setDiameter(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_PLENGTH:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setpLength(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_PWEIGHT:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setpWeight(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_PDEPTH:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setpDepth(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_PDEPTHPER:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setpDepthPer(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_PTABLE:
                        try {
                            new Double(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setpTable(new Double(cellStringValue));
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_LAB:
                        stone.setLab(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_CERTIID:
                        stone.setCertiId(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_STOCKIN:
                        Integer stockIn = 0;
                        if ("是".equals(cellStringValue)) {
                            stockIn = 1;
                        }
                        stone.setStockIn(stockIn);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_STOCKCITY:
                        stone.setStockCity(cellStringValue);
                        break;
                    case ConstantsUtil.STONE_EXCEL_COLUMN_SINGLEPRICE:
                        try {
                            new BigDecimal(cellStringValue);
                        } catch (NumberFormatException e) {
                            message = "解析Excel時發生錯誤,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
                                    + (c + 1) + "]列值類型轉換異常";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                        stone.setSinglePrice(new BigDecimal(cellStringValue));
                        break;
                    default:
                        message = "解析Excel時發生錯誤,第[" + (row.getRowNum() + 1) + "]行,第[" + (c + 1) + "]列不應該有值";
                        resultMap.put("message", message);
                        return resultMap;
                    }
                }
                stone.setIsOnSale(false);
                stone.setIsDelete(false);
                stones.add(stone);
            }
        }
        resultMap.put("message", message);
        resultMap.put("stones", stones);
        return resultMap;
    }

3、導出

	/*
	 * 調用寫入Excel的方法
	 */
	public static void doExpotToExcel(List<Map> params) throws IOException {
		//System.out.println("params===:"+params);
		 writeXlsx("D:/測試寫入XLSX.xls",params);
	}

	public static void main(String[] args) throws IOException {
		writeXlsx("D:/測試寫入XLSX.xls", null);
	}
	/*
	 * 將數據寫入Excel
	 */
	private static void writeXlsx(String fileName, List<Map> params) throws IOException {
        // 創建  
        HSSFWorkbook wb = new HSSFWorkbook();  
        HSSFSheet sheet = wb.createSheet();
        // 創建單元格樣式  
        HSSFCellStyle titleCellStyle = wb.createCellStyle();  
        // 指定單元格居中對齊
        titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
        titleCellStyle.setWrapText(true);//設置自動換行  
        HSSFRow headerRow = sheet.createRow(0);  
        HSSFCell headerCell = null; 
        HSSFFont titleFont = wb.createFont();  
        titleFont.setFontHeightInPoints((short) 14);  
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        titleCellStyle.setFont(titleFont);  
        String[] titles = { "序號", "名稱","型號規格","單位","數量","單價","金額","備註"}; 
        for (int c = 0; c < titles.length; c++) {  
            headerCell = headerRow.createCell(c);  
            headerCell.setCellStyle(titleCellStyle);  
            headerCell.setCellValue(titles[c]);  
            if(c==0){
            	sheet.setColumnWidth(c, (13 * 160));
            }else if(c==1){
            	sheet.setColumnWidth(c, (50 * 160));
            }else if(c==2){
            	sheet.setColumnWidth(c, (50 * 160));
            }else if(c==7){
            	sheet.setColumnWidth(c, (40 * 160));
            }else{
            	sheet.setColumnWidth(c, (13 * 160));
            }
            
        } 
        
        HSSFCell bodyCell = null;
        // 創建單元格樣式  
        HSSFCellStyle cellStyle = wb.createCellStyle();   一、設置背景色:
cellStyle.setFillForegroundColor((short) 13);// 設置背景色  
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 

具體顏色可以參照:http://blog.csdn.NET/qq_27937043/article/details/72779442

二、設置邊框: cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框   cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框   cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框  

cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框 

三、設置居中: cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中   cellStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中   cellStyle.setAlignment(HSSFCellStyle.VERTICAL_BOTTOM);//垂直底部   cellStyle.setAlignment(HSSFCellStyle.VERTICAL_TOP);//垂直頂部 四、設置字體: HSSFFont font = wb.createFont();   font.setFontName("黑體");   font.setFontHeightInPoints((short) 16);//設置字體大小   

font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示  

cellStyle.setFont(font);//選擇創建的字體格式 

五、設置列寬: sheet.setColumnWidth(0, 3766);

//第一個參數代表列id(從0開始),第2個參數代表寬度值  參考 :"2017-06-01"的寬度爲2500 

六、設置自動換行:

cellStyle.setWrapText(true);//設置自動換行 

七、合併單元格: 方法1. 此方法在POI3.8中已經被廢棄,建議使用方法2 Region region1 = new Region(0, (short) 0, 0, (short) 6);//參數1:行號 參數2:起始列號 參數3:行號 參數4:終止列號   方法2 CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11);    //參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列     但應注意兩個構造方法的參數不是一樣的,具體使用哪個取決於POI的不同版本。 sheet.addMergedRegion(region1); // 指定單元格居中對齊,邊框爲細 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //設置水平居中 cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//設置垂直居中 cellStyle.setWrapText(true);//設置自動換行 HSSFFont bodyFont = wb.createFont(); bodyFont.setFontHeightInPoints((short) 11); cellStyle.setFont(bodyFont); //額外的列樣式 HSSFCellStyle cellStyleTemp = wb.createCellStyle(); cellStyleTemp.setAlignment(HSSFCellStyle.ALIGN_CENTER); //設置水平居中 cellStyleTemp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//設置垂直居中 HSSFFont tempFont = wb.createFont(); tempFont.setFontHeightInPoints((short) 13); tempFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); cellStyleTemp.setFont(tempFont); for (int r = 0; r < params.size(); r++) { HSSFRow row = sheet.createRow(r + 1); int c = 0; bodyCell = row.createCell(1); bodyCell.setCellStyle(cellStyleTemp); bodyCell.setCellValue(params.get(r).get("product_name").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("count").toString()); if(params.get(r).get("product_type").toString().equals("")){ bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyleTemp); bodyCell.setCellValue(params.get(r).get("product_name").toString()); }else{ bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_name").toString()); } bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_type").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_unit").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_count").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_unit_price").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_price").toString()); bodyCell = row.createCell(c++); bodyCell.setCellStyle(cellStyle); bodyCell.setCellValue(params.get(r).get("product_remark").toString()); } FileOutputStream fileOut = new FileOutputStream(fileName); wb.write(fileOut); fileOut.close(); System.out.println("Done"); } }


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