springboot 项目普通类、工具类、test测试类中调用mapper或service接口(调用持久化层),运用java解析excel表,拿到表中的数据并批量插入数据库
运用java解析excel表,拿到表中的数据并批量插入数据库
导入Excel表格所需的jar
首先,本文是运用jxl进行excel表的解析,所以我们需要先下载一个jxl.jar的jar包;
并且需要一个与excel表对应的实体类,用于接收excel的数据;
<!-- Excel解析导入数据库所需jar -->
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
其次就是代码部分,我们先编写一个函数,用于读取excel;
该函数会返回execl中的数据,将数据一个一个写入innerList,再将innerList写入outerList
最后返回outerList
//该函数用于读取Excel表的内容
public List readExcel(File file) {
try {
// 创建输入流,读取Excel
InputStream is = new FileInputStream(file.getAbsolutePath());
// jxl提供的Workbook类
Workbook wb = Workbook.getWorkbook(is);
// Excel的页签数量
int sheet_size = wb.getNumberOfSheets();
for (int index = 0; index < sheet_size; index++) {
List<List> outerList=new ArrayList<List>();
// 每个页签创建一个Sheet对象
Sheet sheet = wb.getSheet(index);
// sheet.getRows()返回该页的总行数
for (int i = 0; i < sheet.getRows(); i++) {
List innerList=new ArrayList();
// sheet.getColumns()返回该页的总列数
for (int j = 0; j < sheet.getColumns(); j++) {
String cellinfo = sheet.getCell(j, i).getContents();
if(cellinfo.isEmpty()){
continue;
}
innerList.add(cellinfo);
}
outerList.add(i, innerList);
}
return outerList;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
然后再编写一个函数将文件的路径给解析函数,然后就可以根据解析函数返回的outerList进行循环查看表中的数据;
下面的函数中,直接将拿到的数据赋值给一个对象,然后直接给另一个与数据库连接的int num = userInfoService.regedistUser(userInfo)插入数据库。
public void zhuce() {
List<Users> listUser=new ArrayList<Users>();
File file = new File("E:/Mike/student.xls");//需要解析的excel表,注意表的格式必须为xls
List excelList = readExcel(file);
for (int i = 1; i < excelList.size(); i++) {//循环遍历List中的内容(从第二行开始的,第一行为标题 i=0 为第一行)
List list = (List) excelList.get(i);
int j = 0;
if(j < list.size()) {
Users user=new Users();//新建一个对象,将数据循环赋值给对象
// user.setUsername(list.get(0).toString());
// user.setPassword(list.get(1).toString());
// user.setNo(list.get(2).toString());
// user.setName(list.get(3).toString());
// user.setSex(list.get(4).toString());
// user.setDepartment(list.get(5).toString());
// user.setTelephone(list.get(6).toString());
// user.setEmail(list.get(7).toString());
// user.setUsertype(list.get(8).toString());
// j=10;
// u.add(user);//每解析一行即可得到一个对象,再将对象写到List中
System.out.println(list.get(0).toString()+"........"+list.get(1).toString());
// user.setPhoneNumber("13333331111");
// user.setPassword(MD5Util.encrypt("1234567890"));
user.setPhoneNumber(list.get(0).toString());
user.setPassword(MD5Util.encrypt(list.get(1).toString()));
user.setRole(Short.valueOf("0"));// 普通会员角色0
user.setStatus(Short.valueOf("1"));// 普通会员默认激活
user.setIntegral(0);
user.setGrowthValue(0);
user.setActiveScore(0);
user.setGrade("grade0");
Date date = new Date();
user.setCreatetime(date);
user.setUpdatetime(date);
// 生成随机昵称
char[] temp = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'q', 'w', 'y', 'r', 't', 'u', 'i', 'o', 'p', 'l', 'k',
'j', 's', 'z', 'x', 'v', 'm', 'n', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'Q', 'W', 'Y', 'R', 'T', 'U',
'I', 'O', 'P', 'L', 'K', 'J', 'S', 'Z', 'X', 'V', 'M', 'N' };
StringBuilder nickname = new StringBuilder();
nickname.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()]);
user.setNickname(nickname.toString());
j = 3;
listUser.add(user);//每解析一行即可得到一个对象,再将对象写到List中
}
}
使用for的迭代循环注册
for (Users userInfo : listUser) {
System.out.println(userInfo.getPhoneNumber()+".......................");
int num = userInfoService.regedistUser(userInfo);
if (num == 1) {
System.out.println("注册成功");
} else if (num == -1) {
System.out.println("手机号已注册");
} else {
System.out.println("注册失败");
}
}
}
springboot 项目普通类、工具类、test测试类中调用mapper或service接口(调用持久化层)
springboot 项目普通类、工具类、test测试类中调用mapper或service接口(调用持久化层),由于这是动态扫描得到的,所以需要加注解@RunWith(SpringRunner.class) 、@SpringBootTest、@Test这样Springboot项目全部启动扫描才可以调用mapper或service成功,如果直接用main主函数的方法,main是静态的控制台输出,若是调用mapper或service,控制台会报错 空指针异常!!!!
Exception in thread "main" java.lang.NullPointerException
package com.juyi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.juyi.dao.entity.Users;
import com.juyi.service.UserInfoService;
import com.juyi.util.common.MD5Util;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRegisteTest {
@Autowired
UserInfoService userInfoService;
//该函数用于读取Excel表的内容
public List readExcel(File file) {
try {
// 创建输入流,读取Excel
InputStream is = new FileInputStream(file.getAbsolutePath());
// jxl提供的Workbook类
Workbook wb = Workbook.getWorkbook(is);
// Excel的页签数量
int sheet_size = wb.getNumberOfSheets();
for (int index = 0; index < sheet_size; index++) {
List<List> outerList=new ArrayList<List>();
// 每个页签创建一个Sheet对象
Sheet sheet = wb.getSheet(index);
// sheet.getRows()返回该页的总行数
for (int i = 0; i < sheet.getRows(); i++) {
List innerList=new ArrayList();
// sheet.getColumns()返回该页的总列数
for (int j = 0; j < sheet.getColumns(); j++) {
String cellinfo = sheet.getCell(j, i).getContents();
if(cellinfo.isEmpty()){
continue;
}
innerList.add(cellinfo);
}
outerList.add(i, innerList);
}
return outerList;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Test
public void zhuce() {
List<Users> listUser=new ArrayList<Users>();
File file = new File("E:/Mike/student.xls");//需要解析的excel表,注意表的格式必须为xls
List excelList = readExcel(file);
for (int i = 1; i < excelList.size(); i++) {//循环遍历List中的内容(从第二行开始的,第一行为标题 i=0 为第一行)
List list = (List) excelList.get(i);
int j = 0;
if(j < list.size()) {
Users user=new Users();//新建一个对象,将数据循环赋值给对象
// user.setUsername(list.get(0).toString());
// user.setPassword(list.get(1).toString());
// user.setNo(list.get(2).toString());
// user.setName(list.get(3).toString());
// user.setSex(list.get(4).toString());
// user.setDepartment(list.get(5).toString());
// user.setTelephone(list.get(6).toString());
// user.setEmail(list.get(7).toString());
// user.setUsertype(list.get(8).toString());
// j=10;
// u.add(user);//每解析一行即可得到一个对象,再将对象写到List中
System.out.println(list.get(0).toString()+"........"+list.get(1).toString());
// user.setPhoneNumber("13333331111");
// user.setPassword(MD5Util.encrypt("1234567890"));
user.setPhoneNumber(list.get(0).toString());
user.setPassword(MD5Util.encrypt(list.get(1).toString()));
user.setRole(Short.valueOf("0"));// 普通会员角色0
user.setStatus(Short.valueOf("1"));// 普通会员默认激活
user.setIntegral(0);
user.setGrowthValue(0);
user.setActiveScore(0);
user.setGrade("grade0");
Date date = new Date();
user.setCreatetime(date);
user.setUpdatetime(date);
// 生成随机昵称
char[] temp = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'q', 'w', 'y', 'r', 't', 'u', 'i', 'o', 'p', 'l', 'k',
'j', 's', 'z', 'x', 'v', 'm', 'n', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'Q', 'W', 'Y', 'R', 'T', 'U',
'I', 'O', 'P', 'L', 'K', 'J', 'S', 'Z', 'X', 'V', 'M', 'N' };
StringBuilder nickname = new StringBuilder();
nickname.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()])
.append(temp[new Double(Math.floor(Math.random() * 100000) % 31).intValue()]);
user.setNickname(nickname.toString());
j = 3;
listUser.add(user);//每解析一行即可得到一个对象,再将对象写到List中
}
}
使用for的迭代循环注册
for (Users userInfo : listUser) {
System.out.println(userInfo.getPhoneNumber()+".......................");
int num = userInfoService.regedistUser(userInfo);
if (num == 1) {
System.out.println("注册成功");
} else if (num == -1) {
System.out.println("手机号已注册");
} else {
System.out.println("注册失败");
}
}
}
// public static void main(String[] args) {
// UserRegisteTest urt = new UserRegisteTest();
// urt.zhuce();
// }
}