整体思路:
导入Excel表格,将表格中的数据读取出并导入数据库。
注意:表格中的列的数值获取时要与对象的属性相对应。
1.上传文件时,先根据文件的 后缀,判断excel版本创建对应的Workbook
2.获取IO流中的数据,组装成List>
2.1表格中的数值类型读取时要先进行判断,转成字符串。
3.解析List>将List
步骤一:配置pom依赖
4.0.0
Excel_operation
Excel_operation
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework
spring-webmvc
org.apache.poi
poi
3.9
org.apache.poi
poi-ooxml
3.9
org.springframework.boot
spring-boot-maven-plugin
步骤二:建立一个启动类
package com.excel.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExcelMain {
public static void main(String[] args) {
SpringApplication.run(ExcelMain.class, args);
}
}
步骤三:建立一个实体对象
【实体对象的属性和excel中的列名要对应】
步骤四:编写上传接口
package com.excel.test.im;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.excel.test.entity.Student;
import com.excel.test.util.ExcelUtil;
@RestController
@RequestMapping(value = "/excel")
public class ImportFile {
@Autowired
private ExcelUtil excelUtil;
@RequestMapping(value = "/import")
public String importExcel(HttpServletRequest request) {
//将request转换成一个上传文件的MultipartHttpServletRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("upfile");
InputStream in = null;
List> listObject = null;
try {
if(file.isEmpty()) {
throw new Exception( "文件不存在");
}
in = file.getInputStream();
listObject = excelUtil.getListByExcel(in, file.getOriginalFilename());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
//创建一个List存入对应的对象值
List stuList = new ArrayList();
for(int i = 0;i < listObject.size(); i++) {
//取出List>中的List
其中
根据文件的后缀,自适应上传文件的版本,
获取IO流中的数据,组装成List>,
将字符串转换成日期,
对表格中的数据进行格式化,
自定义处理日期 的处理都在工具类中进行。
package com.excel.test.util;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
@Controller
public class ExcelUtil {
private final static String excel2003L = ".xls"; //2003- 版本的excel
private final static String excel2007L = ".xlsx"; //2007+ 版本的excel
/**
* 根据文件的后缀,自适应上传文件的版本
* @param in
* @param fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream in,String fileName) throws Exception {
Workbook book = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)) {
book = new HSSFWorkbook(in);
}else if(excel2007L.equals(fileType)) {
book = new XSSFWorkbook(in);
}else {
throw new Exception("解析文件格式有误!");
}
return book;
}
/**
* 自定义处理日期
* @author Ejiao
*
*/
public static class XSSFDateUtil extends DateUtil{
protected static int absoluteDay(Calendar cal,boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
/**
* 对表格中的数据进行格式化
* @param cell
* @return
*/
@SuppressWarnings("unused")
public Object getCellValue(Cell cell) {
String strCell = "";
switch(cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING: //字符串
strCell = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BOOLEAN: //判断
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_BLANK: //空白
strCell = "";
break;
case XSSFCell.CELL_TYPE_FORMULA: //公式
strCell = String.valueOf(cell.getNumericCellValue());
DecimalFormat df = new DecimalFormat("#.########");
strCell = df.format(Double.valueOf(strCell));
break;
case XSSFCell.CELL_TYPE_NUMERIC:
if(XSSFDateUtil.isCellDateFormatted(cell)) { //如果是date类型
strCell = new SimpleDateFormat("yyyy-MM-dd").format(XSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}else {
strCell = String.valueOf(cell.getNumericCellValue());
DecimalFormat df1 = new DecimalFormat("#.#########");
strCell=df1.format(Double.valueOf(strCell));
}
break;
default:
strCell = "";
break;
}
if(strCell.equals("") || strCell == null) {
return "";
}
if(cell == null) {
return "";
}
return strCell;
}
/**
* 将字符串转换成日期
* @param str
* @return
*/
public Date parseDate(String str) {
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
try {
return date.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取IO流中的数据,组装成List>
* @param in
* @param fileName
* @return
* @throws Exception
*/
public List> getListByExcel(InputStream in,String fileName) throws Exception{
List> list = new ArrayList>();
Sheet sheet = null;
Row row = null;
Cell cell =null;
//创建Excel工作簿
Workbook book = this.getWorkbook(in, fileName);
if(book == null) {
throw new Exception("创建Exception为空");
}
//遍历Excel中所有的sheet
for(int i = 0;i < book.getNumberOfSheets(); i++) {
sheet = book.getSheetAt(i);
if(sheet != null) {
for(int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++ ) {
row = sheet.getRow(j);
if(row == null || row.getFirstCellNum() == j) {
continue;
}
//遍历所有的列
List li = new ArrayList();
for(int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
}
return list;
}
}