How to read and write excel file

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

    For reading a xlsx file we can use Apache POI libs Try this:

    public static void readXLSXFile() throws IOException
        {
            InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
            XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);
    
            XSSFWorkbook test = new XSSFWorkbook(); 
    
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row; 
            XSSFCell cell;
    
            Iterator rows = sheet.rowIterator();
    
            while (rows.hasNext())
            {
                row=(XSSFRow) rows.next();
                Iterator cells = row.cellIterator();
                while (cells.hasNext())
                {
                    cell=(XSSFCell) cells.next();
    
                    if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                    {
                        System.out.print(cell.getStringCellValue()+" ");
                    }
                    else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                    {
                        System.out.print(cell.getNumericCellValue()+" ");
                    }
                    else
                    {
                        //U Can Handel Boolean, Formula, Errors
                    }
                }
                System.out.println();
            }
    
        }
    

提交回复
热议问题