How to read excel file using spring boot

后端 未结 4 1074
北恋
北恋 2021-02-02 00:46

I am making a spring boot application which will take the excel file and store its content and store it in database. I have tried many ways..but not successful. Is anyone has id

4条回答
  •  隐瞒了意图╮
    2021-02-02 01:16

    Use Apache POI library which is easily available using Maven Dependencies.

    
        org.apache.poi
        poi-ooxml
        3.15
      
    

    Code to read file

    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Iterator;
    
    public class ApachePOIExcelRead {
    
        private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";
    
        public static void main(String[] args) {
    
            try {
    
                FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
                Workbook workbook = new XSSFWorkbook(excelFile);
                Sheet datatypeSheet = workbook.getSheetAt(0);
                Iterator iterator = datatypeSheet.iterator();
    
                while (iterator.hasNext()) {
    
                    Row currentRow = iterator.next();
                    Iterator cellIterator = currentRow.iterator();
    
                    while (cellIterator.hasNext()) {
    
                        Cell currentCell = cellIterator.next();
                        //getCellTypeEnum shown as deprecated for version 3.15
                        //getCellTypeEnum ill be renamed to getCellType starting from version 4.0
                        if (currentCell.getCellTypeEnum() == CellType.STRING) {
                            System.out.print(currentCell.getStringCellValue() + "--");
                        } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                            System.out.print(currentCell.getNumericCellValue() + "--");
                        }
    
                    }
                    System.out.println();
    
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Please modify above program as per your requirement. If you know your excel file column index then you can direct row to read cell e.g.row.getCell(0) where row object like XSSFRow row = (XSSFRow) iterator.next();

    Hope this will helps you

    Reference

提交回复
热议问题