Step 1: write maven dependency (3.6 is a stable version, which can be used in production environment)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.6</version>
</dependency>
Step 2: add the Excl import tool class to the project, use it out of the box, and test the main () method in built-in
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
*
* @ClassName: ImportExcelUtil
* @Description: excel Import data
* @author JonyChen
* @date 2018 August 13th 2013
* @time 10:28:48 am
*/
public class ImportExcelUtil {
private final static String excel2003L =".xls"; //2003- Versions excel
private final static String excel2007U =".xlsx"; //2007+ Versions excel
/**
* Description: get the data in IO stream and assemble it into list < list < Object > > object
* @param file
* @return
* @throws Exception
*/
public List<List<Object>> importExcel(File file) throws Exception{
List<List<Object>> list = null;
//Establish Excel Job shop
Workbook work = this.getWorkbook(file);
if(null == work){
throw new Exception("Establish Excel Workbook is empty!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//ergodic Excel All of them sheet
for (int i = 0; i <work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//Ergodic current sheet All rows in
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//Traverse all columns
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y <row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
return list;
}
/**
* Description: adaptively upload the file version according to the file suffix
* @param file
* @return
* @throws Exception
*/
public Workbook getWorkbook(File file) throws Exception{
Workbook wb = null;
String fileType = file.getName().substring(file.getName().lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(new FileInputStream(file)); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(new FileInputStream(file)); //2007+
}else{
throw new Exception("The format of the parsed file is wrong!");
}
return wb;
}
/**
* Description: formats values in tables
* @param cell
* @return
*/
public Object getCellValue(Cell cell){
//use String Receive all returned values
String value = null;
DecimalFormat df = new DecimalFormat("0"); //Format number String character
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //Date format
DecimalFormat df2 = new DecimalFormat("0.00"); //Formatting Numbers
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: //String Data of type
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: //value type(Use of value cell.getNumericCellValue() or cell.getDateCellValue())
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if(HSSFDateUtil.isCellDateFormatted(cell)){
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean type
value = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //Expression type
value = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_ERROR: //The exception type does not know when it is an exception
value=String.valueOf(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_BLANK: //Empty, I don't know when it's empty
value = "";
break;
default:
value = "";
break;
}
if(value.equals("")||value==null){
value = "";
}
if (cell == null) {
return "";
}
return value;
}
//read excel Field in
public static void main(String[] args){
ImportExcelUtil importExcelUtil=new ImportExcelUtil();
//excel Import data demo
File file = new File("C:\\Users\\srt\\Desktop\\signup_category.xls");
List<List<Object>> dataList= null;
List<SignupCategory> list=new ArrayList<>();
try {
dataList = importExcelUtil.importExcel(file);
} catch (Exception e) {
e.printStackTrace();
}
//Data encapsulation format 1: take out the data traversal in the table and put it into the object List
for (int i = 0; i <dataList.size(); i++) {
Object type_id = dataList.get(i).get(0);
Object type_name = dataList.get(i).get(1);
SignupCategory signupCategory=new SignupCategory();
signupCategory.setTypeId(Integer.parseInt((String)type_id));
signupCategory.setTypeName((String)type_name);
list.add(signupCategory);
System.out.println("------------------");
System.out.println((String)type_id+":"+(String)type_name);
}
System.out.println(JsonUtils.toJson(list));
//Data encapsulation format 2, double loop traversal to extract elements
/*for (int i = 0; i < dataList.size(); i++) {
for (int j = 0; j < dataList.get(i).size(); j++) {
System.out.println(dataList.get(i).get(j));
}
System.out.println("------------------");
}*/
}
}
Step 3: call in the Controller layer
Supplement:
The basic import process is as follows: the front-end page provides the download address of the excl data template. The user clicks the download template excl (in fact, the export of excl), fills in the template, and then uploads it to the server before calling the above tool class to import the real data. The above case only takes the imported data out to the console for viewing. If there is a need to import the database in the later stage , and then it can be expanded. It can be used for personal test. It has corrected other online tutorials. It is currently available!