POI

来源:互联网 发布:恶意软件博物馆 编辑:程序博客网 时间:2024/06/12 01:14

前言

近期由于工作上的需要,需要操作excel,并且需要对excel的数据进行判断,确认是否存在错误.
使用了poi进行操作,简单的记录一下代码.

导入

public class DistributionExcelUtil {    //2003版本的excel    private final static String excel2003 = ".xls";    //2007版本的excel    private final static String excel2007 = ".xlsx";    /**     * 从流中读取excel数据     * @param file spring mvc 上传的文件     * @return     * @throws Exception     */    public static  List getBankListByExcel(MultipartFile file) throws Exception{        List<Map> list = new ArrayList<>();        //创建Excel的workBook        Workbook work = getWorkbook(file.getInputStream(),file.getOriginalFilename());        Sheet sheet = null;        Row row = null;        Cell cell = null;        //遍历Excel中所有的sheet        for (int i = 0; i < work.getNumberOfSheets(); i++) {            sheet = work.getSheetAt(i);            if(sheet==null) continue;            //遍历当前sheet中的所有行,从第二行开始,如果没有头的话 从第一行开始            for (int j = sheet.getFirstRowNum()+1; j <= sheet.getLastRowNum(); j++) {                row = sheet.getRow(j);                if(row==null) continue;                //遍历所有的列 应该使用实际的对象,演示就是用map了                Map detail = new HashMap<>();                //5需要根据你自己的宽度决定,使用数字的原因是因为怕遇到空列导致数据丢失                for (int y = 0; y < 5; y++) {                    Object cellValue = null;                    cell = row.getCell(y);                    switch (y){                        case 0:                            cellValue = getCellValue(cell);                            //扩展业务 对cellValue进行操作                            detail.put(i,cellValue);                            break;                        case 1:                            cellValue = getCellValue(cell);                            if (cellValue instanceof Double){                                detail.put(i,(Double) cellValue);                            }                            detail.put(i,cellValue);                            break;                        default:                            break;                    }                }                list.add(detail);            }        }        work.close();        return list;    }    /**     * 描述:根据文件后缀,自适应上传文件的版本     *     * @param inputStream     * @param fileName     * @return     * @throws Exception     */    public static Workbook getWorkbook(InputStream inputStream, String fileName) throws Exception {        Workbook workbook = null;        String fileType = fileName.substring(fileName.lastIndexOf("."));        if (fileName.endsWith(excel2003)) {            workbook = new HSSFWorkbook(inputStream);        }        else if (fileName.endsWith(excel2007)) {            workbook = new XSSFWorkbook(inputStream);        }        else {            throw new Exception("无法解析文件,请确认格式是否错误!");        }        return workbook;    }    /**     * 对表格中数值进行格式化     * @param cell     * @return     */    public static Object getCellValue(Cell cell) {        if (cell == null) {            return cell;        }        Object value = null;        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化        switch (cell.getCellTypeEnum()) {            case STRING:                value = cell.getRichStringCellValue().getString();                break;            case NUMERIC:                if ("General".equals(cell.getCellStyle().getDataFormatString())) {                    value = cell.getNumericCellValue();                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {                    value = sdf.format(cell.getDateCellValue());                } else {                    value = cell.getNumericCellValue();                }                break;            case BOOLEAN:                value = cell.getBooleanCellValue();                break;            default:                break;        }        return value;    }}

导出

/** * @author Eumji * @date 2017/12/16 */public class ExploreExcelUtil2222222 {    /**     * 通过申请详情的列表生成字节数组流     * 使用的时候把map换成自己需要的对象     * @param list     * @return     * @throws Exception     */    public static void writeFile(List<Map> list) throws Exception {        //表头        String[] title = {"第一列", "第二列", "第三列", "第四列", "第五列"};        //创建excel工作簿        HSSFWorkbook workbook = new HSSFWorkbook();        //创建工作表sheet        HSSFSheet sheet = workbook.createSheet();        //创建第一行        HSSFRow row = sheet.createRow(0);        row.setHeightInPoints((short) 20);        //设置style        row.setRowStyle(getCellStyle(workbook));        HSSFCell cell = null;        //插入第一行数据的表头        for (int i = 0; i < title.length; i++) {            cell = row.createCell(i);            cell.setCellValue(title[i]);        }        /**         * 具体数据插入         */        for (int i = 0; i < list.size(); i++) {            Map map = list.get(i);            HSSFRow nrow = sheet.createRow(i + 1);            HSSFCell ncell = nrow.createCell(0);            //商家名称            if ( map.get(i) != null ) {                ncell.setCellValue(map.get(1));            }            ncell = nrow.createCell(1);            ncell.setCellValue(map.get(2));            ncell = nrow.createCell(2);        }        FileOutputStream stream = new FileOutputStream("path/test.xls");        workbook.write(stream);        stream.flush();        stream.close();    }   public static CellStyle getCellStyle(HSSFWorkbook workbook){       //设置字体       HSSFFont font =workbook.createFont();       font.setFontHeightInPoints((short) 20); //字体高度       font.setColor(HSSFFont.COLOR_NORMAL); //字体颜色       font.setFontName("微软雅黑"); //字体       font.setFontHeightInPoints((short) 14);       //设置单元格类型       HSSFCellStyle cellStyle =workbook.createCellStyle();       cellStyle.setFont(font);       cellStyle.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());       cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平布局:居中       cellStyle.setWrapText(true);       return cellStyle;   }}

结语

poi可定制化强,但是如果大量的不同表格需要操作的话是非常麻烦的,如果不是业务上的需要可以借助其他的jxls绑定模板操作非常的简单便捷.

与君共勉!!!

原创粉丝点击