Java parsing Excel, using InputStream to read the file

一, need to import the jar package

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>

二, POIAPI connection

三, the code is as follows

/**
* Get uploaded excel parsing data
*
* @param file
* Document
* @param excelName
	 *            file name
* @return
* @throws IOException
* @throws InvalidFormatException
*/
@PostMapping("/readexcel")
Public List<WorkstationExcel> uploadExcel(@RequestParam MultipartFile file, @RequestParam String excelName) throws IOException, InvalidFormatException {
List<WorkstationExcel> dataList = null;
Try (InputStream in = file.getInputStream()) {
Workbook wb = WorkbookFactory.create(in);
// Get the first sheet
Sheet sheet = wb.getSheetAt(0);
// Get the maximum number of rows
Int rownum = sheet.getPhysicalNumberOfRows();
/ / Get the first line
Row row = sheet.getRow(0);
/ / Store the data in the table
dataList = new ArrayList<WorkstationExcel>();
// loop line
For (int i = 1; i < rownum; i++) {
WorkstationExcel we = new WorkstationExcel();
Row = sheet.getRow(i);
If (row != null) {
We.name = getCellFormatValue(row.getCell(0));
We.ip = getCellFormatValue(row.getCell(1));
We.description = getCellFormatValue(row.getCell(2));
} else {
Continue;
}
                System.err.println("Name:" + we.name + "------" + "IP:" + we.ip + "------" + "Description:" + we.description );
dataList.add(we);
}
}
Return dataList;
}

Public String getCellFormatValue(Cell cell) {
String cellValue = "";
If (cell == null) {
Return cellValue;
}
/ / Determine the cell type getCellType ()
Switch (cell.getCellType()) {
Case Cell.CELL_TYPE_NUMERIC: {
// Get the value of the cell as a number getNumericCellValue()
cellValue = String.valueOf((int)cell.getNumericCellValue());
Break;
}
Case Cell.CELL_TYPE_FORMULA: {
/ / Determine whether the cell is a date format
If (DateUtil.isCellDateFormatted(cell)) {
// Convert to date format YYYY-mm-dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = cell.getDateCellValue();
If (d != null) {
cellValue = sdf.format(d);
}
} else {
// number
cellValue = String.valueOf(cell.getNumericCellValue());
}
Break;
}
Case Cell.CELL_TYPE_STRING: {
cellValue = cell.getRichStringCellValue().getString();
Break;
}
}
Return cellValue;
}

@SuppressWarnings("unused")
Private class WorkstationExcel {
/**
* Workstation name such as 001
*/
Public String name;
/**
* Workstation ip
*/
Public String ip;
/**
* Description
*/
Public String description;
}

四,Excel table below

IP 描述
GYG4 127.0.0.33 sfs
DFSA 127.0.46.3 fsd
ADAS 172.26.6.15 dfd
WSFS 153.6.5.23 dgs

五,Get data results