首页 > 技术文章 > 基于spring sringmvc mybatis 做的导入导出

pzxbky 2019-03-29 11:02 原文

导入

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.usermanage</groupId>
<artifactId>usermanages</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
<groupId>cn.parent.jar</groupId>
<artifactId>parentjar</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!--上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>

<!-- MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>

<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-spring</artifactId>
</dependency>

<!-- JSP相关 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<!--poi版本要一致才行 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>

</dependencies>

<build>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<configuration>
<port>8088</port>
<path>/</path>
</configuration>
</plugin>

<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <source>1.8</source> <target>1.8</target> </configuration>
</plugin> -->

</plugins>
</build>
</project>

 

 

jsp代码

<div id="dlg" class="easyui-dialog" title="My Dialog"style="width: 400px; height: 200px;"
data-options="title:'导入',resizable:true,modal:true,closed:true,buttons:[{
text:'导入',
handler:function(){
$('#import').submit();
}
}]">
<form id="import" action="http://localhost:8088/user/batchimport"
enctype="multipart/form-data" method="post" onsubmit="return check();">
<div style="margin: 30px;">
<input id="excel_file" type="file" name="filename" accept="xlsx"size="80" />
</div>
<font id="importMsg" color="red" ><%=importMsg%></font>

</form>
</div>

 

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<User> customerList = readExcel.getExcelInfo(name, file);

if (customerList != null) {

// 迭代添加客户信息(注:实际上这里也可以直接将customerList集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。)
List<String> ids = new ArrayList<String>();
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<User> 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<User> customerList = new ArrayList<User>();
// 初始化输入流
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<User> 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();

 

}

 

}

 

推荐阅读