1.导入poi相关jar包。下载地址:http://poi.apache.org/download.html
2.jsp页面用表单上传,表单记得写入enctype="multipart/form-data"用于上传文件。
3.在导入方法加入参数@RequestParam(value = "file", required = false) MultipartFile file
4.Workbook book = this.getWorkbook(file); // 读取excel
public static Workbook getWorkbook(MultipartFile file) throws Exception {
Workbook workbook = null;
String filePath = file.getOriginalFilename();
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
return workbook;
}
for (int i = 1; i <= rows; i++) {// 循环EXCEL文件 获取每行的记录处理数据 从第二行开始
Row row = sheet.getRow(i);//获取第i行
if (row.getCell(0)==null||row.getCell(0).toString().trim().equals("")) {//判断第一列是否为空
continue;
}
row.getCell(0).toString().trim()//获得第一列的值。
CellReference.convertNumToColString(row.getCell(0).getColumnIndex())//可以获得第一列的列名,如A。
(row.getCell(0).getRowIndex()+1)//获得第一行的行号,如1。
...这里可以依次给对象赋值然后进行持久化操作
}
poi-3.16.jar,commons-collections4-4.1.jar )
2.jsp页面用表单上传,表单记得写入enctype="multipart/form-data"用于上传文件。
3.在导入方法加入参数@RequestParam(value = "file", required = false) MultipartFile file
4.Workbook book = this.getWorkbook(file); // 读取excel
public static Workbook getWorkbook(MultipartFile file) throws Exception {
Workbook workbook = null;
String filePath = file.getOriginalFilename();
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
return workbook;
}
5.Sheet sheet = book.getSheetAt(0); // 获得第一个工作表对象
int rows = sheet.getLastRowNum();// 获取所有行数for (int i = 1; i <= rows; i++) {// 循环EXCEL文件 获取每行的记录处理数据 从第二行开始
Row row = sheet.getRow(i);//获取第i行
if (row.getCell(0)==null||row.getCell(0).toString().trim().equals("")) {//判断第一列是否为空
continue;
}
row.getCell(0).toString().trim()//获得第一列的值。
CellReference.convertNumToColString(row.getCell(0).getColumnIndex())//可以获得第一列的列名,如A。
(row.getCell(0).getRowIndex()+1)//获得第一行的行号,如1。
...这里可以依次给对象赋值然后进行持久化操作
}
注意:使用的poi的相关jar包一定版本一定要相同!(poi-ooxml-3.16.jar,poi-ooxml-schemas-3.16.jar,xmlbeans-2.6.0.jar,
poi-3.16.jar,commons-collections4-4.1.jar )