java读取excel文件

摘要:
=null){ListrowData=newArrayList();for{cellData=getCellFormatValue;rowData.add;}list.add;}else{break;}}}returnlist;}//读取excel文件publicstaticWorkbookreadExcel{Workbookwb=null;if{returnnull;}StringextString=filePath.substring;InputStreamis=null;try{is=newFileInputStream;if{returnwb=newHSSFWorkbook;}elseif{returnwb=newXSSFWorkbook;}else{returnwb=null;}}catch{e.printStackTrace();}catch{e.printStackTrace();}returnwb;}//根据excel文件内容数据的不同类型格式化publicstaticObjectgetCellFormatValue{ObjectcellValue=null;if(cell!=null){//判断cell类型switch{caseCell.CELL_TYPE_NUMERIC:{cellValue=String.valueOf;break;}caseCell.CELL_TYPE_FORMULA:{//判断cell是否为日期格式if{//转换为日期格式YYYY-mm-ddcellValue=cell.getDateCellValue();}else{//数字cellValue=String.valueOf;}break;}caseCell.CELL_TYPE_STRING:{cellValue=cell.getRichStringCellValue().getString();break;}default:cellValue="";}}else{cellValue="";}returncellValue;}//写入文件,toExcelMap内容格式为{"第五列":"xxxx","第六列:"xxxx"....}publicstaticvoidwriteExcel{OutputStreamout=null;try{//读取Excel文档WorkbookworkBook=readExcel;//sheet对应一个工作页Sheetsheet=workBook.getSheetAt;/***往Excel中写新数据*/for{try{log.info;Rowrow=sheet.getRow;if{LinkedHashMapinfo=toExcelMap.get;row.createCell.setCellValue(info.get("location")!
    //分析文件,结果为[[第一行的数据],[第二行的数据],.....]
    public static List<List<String>> analysisSheet(String filePath, intcurrentSheet) {
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<List<String>> list = null;
        String cellData = null;
        wb =readExcel(filePath);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<List<String>>();
            //获取第一个sheet
            sheet =wb.getSheetAt(currentSheet);
            //获取最大行数
            int rownum =sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = 0;
            /*获取最大列数 */
            for(int i = 1; i < rownum; i++){
                row =sheet.getRow(i);
                if(row.getPhysicalNumberOfCells()>colnum){
                    colnum =row.getPhysicalNumberOfCells();
                }
            }
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row =sheet.getRow(i);
                if (row != null) {
                    List<String> rowData = new ArrayList<>();
                    for (int j = 0; j < colnum; j++) {
                        cellData =(String) getCellFormatValue(row.getCell(j));
                        rowData.add(cellData);
                    }
                    list.add(rowData);
                } else{
                    break;
                }
            }
        }
        returnlist;
    }

    //读取excel文件
    public staticWorkbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try{
            is = newFileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = newHSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = newXSSFWorkbook(is);
            } else{
                return wb = null;
            }
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        returnwb;
    }
    //根据excel文件内容数据的不同类型格式化
    public staticObject getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            switch(cell.getCellType()) {
                caseCell.CELL_TYPE_NUMERIC: {
                    cellValue =String.valueOf(cell.getNumericCellValue());
                    break;
                }
                caseCell.CELL_TYPE_FORMULA: {
                    //判断cell是否为日期格式
                    if(DateUtil.isCellDateFormatted(cell)) {
                        //转换为日期格式YYYY-mm-dd
                        cellValue =cell.getDateCellValue();
                    } else{
                        //数字
                        cellValue =String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                caseCell.CELL_TYPE_STRING: {
                    cellValue =cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else{
            cellValue = "";
        }
        returncellValue;
    }
    //写入文件,toExcelMap内容格式为{"第五列":"xxxx","第六列:"xxxx"....}
    public static void writeExcel(ConcurrentHashMap<Integer, LinkedHashMap<String,Object>> toExcelMap, intcurrentSheet, String filePath) {
        OutputStream out = null;
        try{
            //读取Excel文档
            Workbook workBook =readExcel(filePath);
            //sheet 对应一个工作页
            Sheet sheet =workBook.getSheetAt(currentSheet);

            /*** 往Excel中写新数据
             */
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                try{
                    log.info("写入第{}条", i);
                    Row row =sheet.getRow(i);
                    if(toExcelMap.containsKey(i)) {
                        LinkedHashMap<String, Object> info =toExcelMap.get(i);
                        row.createCell(START_COLUMN).setCellValue(info.get("location") != null ? info.get("location").toString() : null);
                        row.createCell(START_COLUMN + 1).setCellValue(info.get("status") != null ? info.get("status").toString() : null);
                        row.createCell(START_COLUMN + 2).setCellValue(info.get("count") != null ? info.get("count").toString() : null);
                    }
                }catch(Exception e) {
                    errorWriteList.add(e);
                }
            }
            System.out.println(errorWriteList);

            //创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
            out = newFileOutputStream(filePath);
            workBook.write(out);
            System.out.println("------- 数据导出成功(filePath"+filePath+") -------");
        } catch(Exception e) {
            e.printStackTrace();
            System.out.println("------- 数据导出失败 -------");
        } finally{
            try{
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

免责声明:文章转载自《java读取excel文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇HBase的Write Ahead Log (WAL) —— 整体架构、线程模型C Primer+Plus(一)概览下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java使用jsoup时绕过https证书验证

详细错误信息: SunCertPathBuilderException: unable to find valid certification path to requested target 问题原因:爬相关数据,因该网站有SSL加密,故无法爬取。 问题解决之核心代码: /** * 绕过HTTPS验证 */ static publi...

delphi计算两个时间差-转

uses DateUtils;   var S1, S2: string; T1, T2: TDateTime; D, H, M, S: Integer; Value: Int64; begin S1 := '2015/09/23 15:44:50'; S2 := '2013/09/22 16:47:51'; T1 := Str...

黑马程序员----java基础--String字符串

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ------- 一、String类概述 java中用String类进行描述对字符串进行了对象的封装。这样的好处是可以对字符串这种常见数据进行方便的操作。对象封装后,可以定义N多属性和行为。 String类是final的,也就是说它没有子类。 二、String字符串的特点...

公众号开发笔记二

前言 微信公众平台开发模板消息,用于公众号向用户发送服务通知,如学生进校门,用校卡滴,就可以在公众号接收服务通知,表明学生进校.在公众号内申请功能,添加模板消息. 只有认证后的服务号才能申请模板消息,需要选择2个行业,MP(维基百科,自由的百科全书),模板消息需要模板的ID,和模板中各种参数,内容以".DATA"结尾,否则视为保留字,模板保留符号"{{...

POI读取公式的值

excel中的数据: packagepoi; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importorg.apache.poi.hssf.usermodel.HSSFWorkbook; importorg.apac...

Sonar常见的审查结果

格式:问题名字+问题出现的次数 Resources should be closed2 资源未关闭,打开发现有两处用到的IO流没有关闭 Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"1 if/else判断里出现了重复判断,比如在if(a>10)的执行体里面...