How to read and write excel file

后端 未结 22 2978
北荒
北荒 2020-11-22 04:49

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to

22条回答
  •  一整个雨季
    2020-11-22 05:08

    I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them

      try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;
    
    int rows; // No of rows
    rows = sheet.getPhysicalNumberOfRows();
    
    int cols = 0; // No of columns
    int tmp = 0;
    int cblacks=0;
    
    // This trick ensures that we get the data properly even if it doesn't start from first few rows
    for(int i = 0; i <= 10 || i <= rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
        }
    
        cols++;
    }
    cols=cols+cblacks;
    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell(c);
                if(cell != null) {
                    System.out.print(cell+"\n");//Your Code here
                }
            }
        }
    }} catch(Exception ioe) {
    ioe.printStackTrace();}
    

提交回复
热议问题