基于spring sringmvc mybatis 做的导入导出
阅读原文时间:2023年07月09日阅读:1

导入

pom.xml

http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
cn.usermanage
usermanages
0.0.1-SNAPSHOT
war

cn.parent.jar parentjar 0.0.1-SNAPSHOT


junit junit test


commons-fileupload commons-fileupload
org.springframework spring-webmvc
org.springframework spring-jdbc
org.springframework spring-aspects


org.mybatis mybatis
org.mybatis mybatis-spring


mysql mysql-connector-java

org.slf4j slf4j-log4j12


com.fasterxml.jackson.core jackson-databind
com.alibaba druid


com.jolbox bonecp-spring


jstl jstl
javax.servlet servlet-api provided
javax.servlet jsp-api provided


org.apache.poi poi 3.9

org.apache.poi poi-ooxml 3.9



org.apache.tomcat.maven tomcat6-maven-plugin 8088 /



jsp代码

<%=importMsg%>

function append(){
$("#dlg").dialog('open');
}

调用方法弹出导入选择框

append()

controller层

/**
* 批量导入数据到数据库
*/
@RequestMapping(value = "batchimport", method = RequestMethod.POST)
public String importDatasource(
@RequestParam(value = "filename") MultipartFile file,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
// 判断文件是否为空
if (file == null)
return null;
// 获取文件名
String name = file.getOriginalFilename();
// 进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
long size = file.getSize();
if (name == null || ("").equals(name) && size == 0)
return null;

// 批量导入。参数:文件名,文件。
boolean b = userService.importDatasource(name, file);
if (b) {
String Msg = "导入成功!";
request.getSession().setAttribute("msg", Msg);
} else {
String Msg = "导入失败,可能是id重复!";
request.getSession().setAttribute("msg", Msg);
}
return "homepage";
}

service 层

boolean importDatasource(String name, MultipartFile file);

serviceImpl层

public class WDWUtil {
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}

//@描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}

/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null
|| !(WDWUtil.isExcel2003(filePath) || WDWUtil
.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}

@Override
public boolean importDatasource(String name, MultipartFile file) {
boolean b = false;
// 创建处理EXCEL
ReadExcel readExcel = new ReadExcel();
// 解析excel,获取客户信息集合。
List customerList = readExcel.getExcelInfo(name, file);

if (customerList != null) {

// 迭代添加客户信息(注:实际上这里也可以直接将customerList集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。)
List ids = new ArrayList();
for (User user : customerList) {
ids.add(user.getId());
}
// 判断导入的数据是否有重复的数据
int countid = userMapper.queryUserById(ids);
if (countid == 0) {
for (User user : customerList) {

userMapper.addUser(user);
}
b = true;
return b;
} else {
return b;
}
} else {
return b;
}

}

/**
* 读EXCEL文件,获取客户信息集合
*
* @param fielName
* @return
*/
public List getExcelInfo(String fileName, MultipartFile Mfile) {

// 把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; // 获取本地存储路径
File file = new File("D:\\fileupload");
// 创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
if (!file.exists())
file.mkdirs();
// 新建一个文件
File file1 = new File("D:\\fileupload\\" + new Date().getTime() + ".xlsx");
// 将上传的文件写入新建的文件中
try {
cf.getFileItem().write(file1);
} catch (Exception e) {
e.printStackTrace();
}

// 初始化客户信息的集合
List customerList = new ArrayList();
// 初始化输入流
InputStream is = null;
try {
// 验证文件名是否合格
if (!validateExcel(fileName)) {
return null;
}
// 根据文件名判断文件是2003版本还是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
// 根据新建的文件实例化输入流
is = new FileInputStream(file1);
// 根据excel里面的内容读取客户信息
customerList = getExcelInfo(is, isExcel2003);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return customerList;
}

导出

controller层
/**
* 导出数据到exce
*
* @param response
* @return
*/
@RequestMapping(value = "export")
public @ResponseBody String exportExcel(HttpServletResponse response,@Param("page")int page,@Param("rows")int rows) {

try {
ServletOutputStream out = response.getOutputStream();
String fileName = new String(("UserInfo " + new SimpleDateFormat(
"yyyy-MM-dd").format(new Date())).getBytes(), "UTF-8");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName + ".xls");
String[] titles = { "密码", "姓名", "id", "年龄", "用户名" };
userService.export(titles, out,(page-1)*rows,rows);
return "导入数据成功";
} catch (Exception e) {
e.printStackTrace();
return "导出信息失败";
}

}

service 层

public void export(String[] titles, ServletOutputStream out, int start, int rows);

serviceImpl 层

@Override
public void export(String[] titles, ServletOutputStream out, int start,
int rows) {
try {
// 第一步,创建一个workbook,对应一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet hssfSheet = workbook.createSheet("sheet1");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow hssfRow = hssfSheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
// 居中样式
hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFCell hssfCell = null;
for (int i = 0; i < titles.length; i++) {
hssfCell = hssfRow.createCell(i);// 列索引从0开始
hssfCell.setCellValue(titles[i]);// 列名1
hssfCell.setCellStyle(hssfCellStyle);// 列居中显示
}

// 第五步,写入实体数据
List users = userMapper.query(start, rows);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (users != null && !users.isEmpty()) {
for (int i = 0; i < users.size(); i++) {
hssfRow = hssfSheet.createRow(i + 1);
User user = users.get(i);

// 第六步,创建单元格,并设置值
String userid = "0";
if (user.getId() != "0") {
userid = user.getId();
}
hssfRow.createCell(2).setCellValue(userid);
String username = "";
if (user.getName() != null) {
username = user.getName();
}
hssfRow.createCell(1).setCellValue(username);
String password = "";
if (user.getPassword() != null) {
password = user.getPassword();
}
hssfRow.createCell(0).setCellValue(password);
String age = "0";
if (user.getAge() != "0") {
age = user.getAge();
}
hssfRow.createCell(3).setCellValue(age);
String userName = "";
if (user.getUserName() != "") {
userName = user.getUserName();
}
hssfRow.createCell(4).setCellValue(userName);
}
}

// 第七步,将文件输出到客户端浏览器
try {
workbook.write(out);
out.flush();
out.close();

} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();

}

}