JavaAPI-poi reads Excel files, javaapi-poiexcel
【First blog posting] The project encountered the need to read the Excel file content. I checked a wave of information online and found that poi is easy to use. record it.
A small DEMO is implemented, and only the first sheet is taken. The function parameter is the file address, returns a two-dimensional list, and is compatible with two Excel formats. Code:
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
Public static ArrayList <ArrayList> readExcelData (String dataPath) throws IOException {ArrayList <Map> resultData = new ArrayList <> (); FileInputStream FCM = new FileInputStream (dataPath ); workbook workbook = null; // determine the excel format xls, xlsx if (dataPath. toLowerCase (). endsWith ("xlsx") {workbook = new XSSFWorkbook (SOx);} else if (dataPath. toLowerCase (). endsWith ("xls") {workbook = new HSSFWorkbook (SOx);} // get 1st sheet Sheet sheet = workbook. getSheetAt (0); // get the Row Iterator <Row> rowIterator = sheet. iterator (); // loop each row while (rowIterator. hasNext () {// get the Row object row = rowIterator. next (); // skip the first line title if (row. getRowNum () = 0) {continue;} ArrayList <Object> cellData = new ArrayList <> (); // loop each column for (int j = 0; j <row. getLastCellNum (); j ++) {// obtain the Cell Object cell = row. getCell (j); // check the data type switch (cell. getCellTypeEnum () {case STRING: cellData. add (cell. getStringCellValue (); break; case BLANK: cellData. add (""); break; case NUMERIC: if (HSSFDateUtil. isCellDateFormatted (cell) // Date judgment {SimpleDateFormat sdf = null; sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); date Date = cell. getDateCellValue (); cellData. add (sdf. format (date);} else {// The number is cellData if it is not a date. add (cell. getNumericCellValue ();} break;} resultData. add (cellData);} FCM. close (); return resultData ;}