How to read and write excel file

后端 未结 22 3201
北荒
北荒 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 04:53

    Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.

         public class ExcelUtils {
         private static XSSFSheet ExcelWSheet;
         private static XSSFWorkbook ExcelWBook;
         private static XSSFCell Cell;
         private static XSSFRow Row;
         File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
         public void setExcelFile(File Path, String SheetName) throws Exception                
    
        try {
            FileInputStream ExcelFile = new FileInputStream(Path);
            ExcelWBook = new XSSFWorkbook(ExcelFile);
            ExcelWSheet = ExcelWBook.getSheet(SheetName);
        } catch (Exception e) {
            throw (e);
        }
    
    }
    
    
          public static String getCellData(int RowNum, int ColNum) throws Exception {
    
        try {
            Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            String CellData = Cell.getStringCellValue();
            return CellData;
        } catch (Exception e) {
    
            return "";
    
        }
    
    }
    public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
    
        try {
            Row = ExcelWSheet.createRow(RowNum - 1);
            Cell = Row.createCell(ColNum - 1);
            Cell.setCellValue(Result);
            FileOutputStream fileOut = new FileOutputStream(Path);
            ExcelWBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        } catch (Exception e) {
    
            throw (e);
    
        }
    
    }
    
    }
    

提交回复
热议问题