excel表格 xls、xlsx 读取

    
    public static void main(String[] args) throws Exception {  
//        getdslContext();  
        String file = "F:\\Python\\最美移动人.xls";

        FileInputStream fs=new FileInputStream(file);  //获取d://test.xls  
        if ("xls".equals(file.split("\\.")[1])) {
            POIFSFileSystem ps=new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息  
            HSSFWorkbook wb=new HSSFWorkbook(ps);    
            HSSFSheet sheet=wb.getSheetAt(0);  //获取到工作表,因为一个excel可能有多个工作表  
//            System.out.println(sheet.getLastRowNum()+" "+row.getLastCellNum());  //分别得到最后一行的行号,和一条记录的最后一个单元格  
            System.out.println(sheet.getLastRowNum());
            for (int i = 3; i < sheet.getLastRowNum() -1; i++) {
                HSSFRow row=sheet.getRow(i);  //获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值  
//                updateDeeds(row.getCell(3).toString(), row.getCell(10).toString());
                System.out.println(row.getCell(1).toString() + "=====" + row.getCell(3).toString());
            }
        }else {
            XSSFWorkbook wb=new XSSFWorkbook(fs);    
            XSSFSheet sheet=wb.getSheetAt(0);  //获取到工作表,因为一个excel可能有多个工作表  
            for (int i = 2; i < sheet.getLastRowNum(); i++) {
                XSSFRow row=sheet.getRow(i);  //获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值  
                for (int j = 0; j < 9; j++) {
                    System.out.print(row.getCell(j));
                    System.out.print("    ");
                }
                System.out.println("");
            }
        }
        fs.close();
    }  

引入jar包

pom.xml

            
        <!-- maven poi -->
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <!-- maven poi end -->

代码:

猜你喜欢

转载自www.cnblogs.com/chen-lhx/p/9288104.html