SSM项目开发难题(一)
如何为用户提供将excel中的数据批量导入至系统数据库呢?
Maven依赖坐标导入
文件上传模块依赖
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
excel导入、导出相关依赖
<!--导入excel相关包-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>4.0.0</version>
</dependency>
一、首先需要一个excelUtil类
package com.ysc.utils;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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;
public class ExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName
* @return
* @throws IOException
*/
public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null; //页数
Row row = null; //行数
Cell cell = null; //列数
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
// 将最大的列数记录下来
int lastCellNum = 0;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
// 比较当前行的列数跟表的最大的列数
if (j == sheet.getFirstRowNum()) {
// 将第一行的列数设为最大
lastCellNum = row.getLastCellNum();
}else {
lastCellNum = lastCellNum > row.getLastCellNum() ? lastCellNum : row.getLastCellNum();
}
for (int y = row.getFirstCellNum(); y < lastCellNum; y++) {
cell = row.getCell(y);
li.add(this.getValue(cell));
}
list.add(li);
}
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
//解决excel类型问题,获得数值
public String getValue(Cell cell) {
String value = "";
if(null==cell){
return value;
}
switch (cell.getCellType()) {
//数值型
case NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//如果是date类型则 ,获取该cell的date值
Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
// 根据自己的实际情况,excel表中的时间格式是yyyy-MM-dd HH:mm:ss还是yyyy-MM-dd,或者其他类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 由于方法的返回值类型为String,这里将Date类型转为String,便于统一返回数据
value = format.format(date);;
}else {// 纯数字
BigDecimal big=new BigDecimal(cell.getNumericCellValue());
value = big.toString();
//解决1234.0 去掉后面的.0
if(null!=value&&!"".equals(value.trim())){
String[] item = value.split("[.]");
if(1<item.length&&"0".equals(item[1])){
value=item[0];
}
}
}
break;
//字符串类型
case STRING:
value = cell.getStringCellValue().toString();
break;
// 公式类型
case FORMULA:
//读公式计算值
value = String.valueOf(cell.getNumericCellValue());
if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
value = cell.getStringCellValue().toString();
}
break;
// 布尔类型
case BOOLEAN:
value = " "+ cell.getBooleanCellValue();
break;
default:
value = cell.getStringCellValue().toString();
}
if("null".endsWith(value.trim())){
value="";
}
return value;
}
}
以字段最少的角色为例,批量添加角色
二、domain编写
role实体类
package com.ysc.domain;
import java.io.Serializable;
import java.util.List;
public class Role implements Serializable {
private Integer id;
private String rname;
private List<User> users;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", rname='" + rname + '\'' +
", users=" + users +
'}';
}
}
三、dao持久层编写
只需要一条插入role的方法
@Repository
public interface RoleDao {
@Insert("insert into role(rname) values(#{rname})")
public int insertRole(String rname);
}
四、service层编写
只需一个用于excel文件内容插入数据库的方法
/**
* 用于excel文件内容插入数据库
* @return
*/
public boolean ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws Exception;
实现类方法重写
/**
* excel文件导入
* @return
*/
@Override
public boolean ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws Exception {
//file即接收到的excel文件
if(file.isEmpty()){
try {
throw new Exception("文件不存在!");
} catch (Exception e) {
e.printStackTrace();
}
}
//将文件导入流
InputStream in =null;
try {
in = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
List<List<Object>> listob = null;
try {
listob = new ExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
//该处可调用service相应方法进行数据保存到数据库中
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
//根据想要导入的内容而定实体类,这里想导入角色选择Role实体类及他的插入方法
Role vo = new Role();
vo.setRname(String.valueOf(lo.get(0))); // 表格的第一列 注意数据格式需要对应实体类属性
System.out.println("从excel中读取的实体类对象:"+ vo);
roleDao.insertRole(vo.getRname());
}
System.out.println("文件导入成功!");
return true;
}
五、Controller层编写
@Controller
@RequestMapping("/admin_role")
public class RoleController {
@Autowired
private RoleService roleService;
//upload即接收到的excel文件。
@RequestMapping("/onloadexcel")
@ResponseBody
public Result onloadExcel(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws Exception {
boolean b = roleService.ajaxUploadExcel(request, response,upload);
if (b==true){
return ResultUtil.success("上传成功,数据已添加至数据库");
}else {
return ResultUtil.error("上传失败,出现未知错误");
}
}
}
六、springmvc.xml配置
配置文件解析器
maxUploadSize是最大文件上传大小
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>
七、前端页面代码编写
其中name="upload"这个name必须与后台的MultipartFile upload这个定义名称相同,后台才能接收文件
<form action="admin_role/onloadexcel" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br/>
<input type="submit" value="上传"/>
</form>
八、测试
因为我的主键id是自增的,所以我只需提供角色名称。
将该excel导入,上传文件
获得添加成功提示
https://blog.csdn.net/linmengmeng_1314/article/details/83093908