1. 程式人生 > >Java-POI,Excel相關

Java-POI,Excel相關

匯入excel讀取裡面內容儲存,建立excel模板

POIUtil類

/*獲取一行指定名的集合*/
/*讀取一行存為list,性別資料庫為int,所以判斷;index=3為年齡,excel裡是String型別,
資料庫為int型別,若未填寫,int存0*/
    public static List<Object> getListByRow(Map<String, String> headDataMap, Row row, String[] attributes) {
        List<Object> datas = new ArrayList<Object>();
        for (int i = 0; i < attributes.length; i++) {
            String index =  headDataMap.get(attributes[i]);
            if(index == null){
                System.out.println("查詢列:"+attributes[i]+"沒有!");
            }
            else{
                Cell cell = row.getCell(Integer.parseInt(index));
                Object cellValue = getCellValue(cell);

                if(index.equals("2")){
                    if(cellValue.equals("女")){
                        cellValue = 1 ;
                    }else {
                    cellValue = 0 ;}
                }
                if(index.equals("3")){
                    if(cellValue.equals("")){
                        cellValue = 0;
                    }
                    cellValue =  Integer.parseInt(cellValue.toString());
                }
                if (cellValue == null) {
                    cellValue = "";
                }
                datas.add(cellValue);
            }

        }
        return datas;
    }

/**
     * 獲取一行的內容,Map儲存,儲存方式由引數定義,獲取表頭
     * @param row 行物件
     *            isValueKey 是否以單元格內容作為Key?key為單元格內容, value為下標索引
     * @return 一行的內容,Map儲存
     */
    public static Map<String, String> getRowDataToMap(Row row, boolean isValueKey) {
        Map<String, String> headDatas = new HashMap<String, String>();
        short countCellNum = row.getLastCellNum();
        if (isValueKey) {
            for (int j = 0; j < countCellNum; j++) {
                Cell cell = row.getCell(j);
                if (isExist(cell)) {
                    // Key=單元格內容, Value=下標索引
                    headDatas.put(String.valueOf(getCellValue(cell)), String.valueOf(j));
                }
            }
        } else {
            for (int j = 0; j < countCellNum; j++) {
                Cell cell = row.getCell(j);
                if (isExist(cell)) {
                    // Key=下標索引, Value=單元格內容
                    headDatas.put( String.valueOf(j), String.valueOf(getCellValue(cell)));
                }
            }
        }
        return headDatas;

    }


/*生成學生Excel表的模板*/
public boolean creatExcel(String path) throws IOException {
        String[] title={ "學號", "姓名", "性別", "年齡",
                "電話", "郵箱", "身份證"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFFont font = wb.createFont();//建立字型樣式
        font.setFontName("宋體");//使用宋體
        font.setFontHeightInPoints((short) 12);//字型大小
        HSSFCellStyle style1 = wb.createCellStyle();
        style1.setFont(font);//將字型注入
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

        HSSFSheet sheet = wb.createSheet("學生資訊表");
        sheet.setColumnWidth(0, 30*170);
        sheet.setColumnWidth(1, 30*170);
        sheet.setColumnWidth(2, 30*128);
        sheet.setColumnWidth(3, 30*128);
        sheet.setColumnWidth(4, 30*160);
        sheet.setColumnWidth(5, 30*170);
        sheet.setColumnWidth(6, 30*250);
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        //插入第一行資料的表頭
        for(int i=0;i<title.length;i++){
            cell=row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellStyle(style1);
        }

		//	旁邊的說明資訊
        sheet.addMergedRegion(new CellRangeAddress(0,(short)2,7,(short)12));
        HSSFFont font1 = wb.createFont();//建立字型樣式
        font1.setFontName("宋體");//使用宋體
        font1.setFontHeightInPoints((short) 14);//字型大小
        font1.setColor(HSSFColor.RED.index);
        HSSFCellStyle style2 = wb.createCellStyle();
        style2.setFont(font1);
        style2.setWrapText(true);// 自動換行
        cell = row.createCell(7);
        cell.setCellValue("性別填:男/女--年齡寫數字,不加歲,如21,23");
        cell.setCellStyle(style2);


        //引數為(第一行,最後一行,第一列,最後一列)
        FileOutputStream os = new FileOutputStream(path+"學生資訊表.xls");
        wb.write(os);
        os.close();
        return true;
    }

 /*獲取單元格資料型別返回值*/
    protected static Object getCellValue(Cell cell) {
        Object cellVauue = "";
        int cellType = 3;
        if(cell!=null) {
            cellType = cell.getCellType();
        }
        switch (cellType) {
            case Cell.CELL_TYPE_BOOLEAN:
                cellVauue = "";
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellVauue = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if(String.valueOf(cell.getNumericCellValue()).indexOf("E")==-1){
                    cellVauue = (int)cell.getNumericCellValue();
                }else {
                    cellVauue =  new DecimalFormat("#").format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_STRING:

                cellVauue = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                cellVauue = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                cellVauue = "";
                break;
            default:
                cellVauue = "";
        }
        if(cellVauue == null){
            cellVauue = "";
        }
        return cellVauue;
    }

Resource類

 @POST
    @Path("importExcel")
    @ApiOperation("學生Excel匯入")
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> studentExcelImport(@FormDataParam("file") FormDataBodyPart file, @BeanParam Student student) throws IOException {
            String mediaType = file.getMediaType().toString();
            //xlsx,xls
        if (!mediaType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && 
                !mediaType.equals("application/vnd.ms-excel")) {
            Checkers.checkState(false, "檔案不是excel型別");
        }
            File entity = file.getEntityAs(File.class);
        return studentService.studentExcelImport(entity,student);
    }

ServiceImpl實現類

 @Override
    public List<String> studentExcelImport(File file , Student student) throws IOException {
        /*if (!xlsPath.endsWith(".xls") && !xlsPath.endsWith(".xlsx")) {
            Checkers.checkState(false, "檔案不是excel型別");
        }*/
        List<String> list = new ArrayList();
        FileInputStream fileIn = new FileInputStream(file);
        Workbook wb = new HSSFWorkbook(fileIn);
    /*    if(xlsPath.endsWith(".xls")){
            wb = new HSSFWorkbook(fileIn);//03版
        }else {
            wb = new XSSFWorkbook(fileIn);//07版不行
        }*/
        Sheet sht0 = wb.getSheetAt(0); //獲取Excel文件中的第一個表單
        Map<String, String> headMap = poiUtil.getRowDataToMap(sht0.getRow(0),false);//獲取表頭
   
        for (int i = 1; i <= sht0.getLastRowNum(); i++) {
            Row row = sht0.getRow(i);
           Student s = new Student();
           s.setSchId(student.getSchId());
           s.setFacId(student.getFacId());
           s.setSpeId(student.getSpeId());
           s.setClaId(student.getClaId());
           for (int j=0;j<row.getLastCellNum();j++){
            switch (headMap.get(String.valueOf(j))) {
                case "學號":
                    if(poiUtil.getCellValue(row.getCell(j)).toString().equals("")){
                        break;
                    }
                    s.setAccount(poiUtil.getCellValue(row.getCell(j)).toString());
                    break;
                case "姓名":
                    if(poiUtil.getCellValue(row.getCell(j)).toString().equals("")){
                        break;
                    }
                    s.setName(poiUtil.getCellValue(row.getCell(j)).toString());
                    break;
                case "性別":
                    int sex;
                    if (poiUtil.getCellValue(row.getCell(j)).equals("女")) {
                        sex = 1;
                    } else {
                        sex = 0;
                    }
                    s.setSex(sex);
                    break;
                case "年齡":
                    String ss = poiUtil.getCellValue(row.getCell(j)).toString();
                    if (ss.equals("")) {
                        s.setAge(0);
                    } else {
                        s.setAge(Integer.parseInt(ss));
                    }
                    break;
                case "電話":
                    if(poiUtil.getCellValue(row.getCell(j)).toString().equals("")){
                        break;
                    }
                    s.setPhone(poiUtil.getCellValue(row.getCell(j)).toString());
                    break;
                case "郵箱":
                    if(poiUtil.getCellValue(row.getCell(j)).toString().equals("")){
                        break;
                    }
                    s.setEmail(poiUtil.getCellValue(row.getCell(j)).toString());
                    break;
                case "身份證":
                    if(poiUtil.getCellValue(row.getCell(j)).toString().equals("")){
                        break;
                    }
                    s.setIdCard(poiUtil.getCellValue(row.getCell(j)).toString());
                    break;
                }
           }

            if(isStudentExist(s.getAccount())){
                list.add("第"+i+"行:"+s.getAccount()+"學生學號重複");
                continue;//庫中已有
            }else if(s.getAccount()==null){
                list.add("第"+i+"行:"+s.getName()+"學生沒有學號");
                continue;//庫中已有
            }else {
                importSave(s);
            }
        }
            fileIn.close();
        return list;
    }

生成Excel模板 具體實現

poi讀取電話號碼一類大數字時會變成帶E的數 解決方法