How to read and write excel file

后端 未结 22 2627
北荒
北荒 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:54

    Try the Apache POI HSSF. Here's an example on how to read an excel file:

    try {
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
        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;
    
        // 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;
            }
        }
    
        for(int r = 0; r < rows; r++) {
            row = sheet.getRow(r);
            if(row != null) {
                for(int c = 0; c < cols; c++) {
                    cell = row.getCell((short)c);
                    if(cell != null) {
                        // Your code here
                    }
                }
            }
        }
    } catch(Exception ioe) {
        ioe.printStackTrace();
    }
    

    On the documentation page you also have examples of how to write to excel files.

提交回复
热议问题