导入

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();

}

}

基于spring sringmvc mybatis 做的导入导出的更多相关文章

  1. Intellij Idea下搭建基于Spring+SpringMvc+MyBatis的WebApi接口架构

    2018-08-16 09:27 更新 强烈推荐使用Springboot来搭建MVC框架! 强烈推荐使用Springboot来搭建MVC框架! 强烈推荐使用Springboot来搭建MVC框架! 后文 ...

  2. 基于Spring+SpringMVC+Mybatis的Web系统搭建

    系统搭建的配置大同小异,本文在前人的基础上做了些许的改动,重写数据库,增加依据权限的动态菜单的实现,也增加了后台返回json格式数据的配置,详细参见完整源码. 主要的后端架构:Spring+Sprin ...

  3. OSGI企业应用开发(十五)基于Spring、Mybatis、Spring MVC实现一个登录应用

    前面文章中,我们已经完成了OSGI应用中Spring.Mybatis.Spring MVC的整合,本篇文章我们就在这个基础上来完成一个简单的登录应用,其中用户名和密码需要从数据库中查询. 前面文章中, ...

  4. 基于 Spring + Atomikos + Mybatis的多数据源配置demo

    1.spring配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...

  5. Spring MVC 实现Excel的导入导出功能(1:Excel的导入)

    简介 这篇文章主要记录自己学习上传和导出Excel时的一些心得,企业办公系统的开发中,经常会收到这样的需求:批量录入数据.数据报表使用 Excel 打开,或者职能部门同事要打印 Excel 文件,而他 ...

  6. 基于spring和mybatis的简单项目流程

    Mybatis整合Spring配置 第一部分:配置Spring框架 配置SpringMVC的步骤 配置流程图 SpringMVC配置 导入包(基本包5个,1日志依赖包,2webmvc支持包) 构建一个 ...

  7. 基于Spring和Mybatis拦截器实现数据库操作读写分离

    首先需要配置好数据库的主从同步: 上一篇文章中有写到:https://www.cnblogs.com/xuyiqing/p/10647133.html 为什么要进行读写分离呢? 通常的Web应用大多数 ...

  8. Spring MVC 实现Excel的导入导出功能(2:Excel的导入优化和Excel的导出)

    Excel的导入V2优化版 有些时候文件上传这一步骤由前端来处理,只将上传后的 URL 传输给后端(可以参考上一文中的图片上传功能),也就是导入请求中并不会直接处理 MultipartFile 对象, ...

  9. 基于多用户的Oracle数据泵导入导出数据

    登陆SqlPlus: SqlPlus sys/syspwd@MyOrcl AS sysdba 其中:syspwd:sys的登陆密码:MyOrcl:所创建的数据库服务名. 创建数据泵: create o ...

随机推荐

  1. elasitcsearch单机版安装

    1.下载压缩包 https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.6.2.tar.gz 2.解压修改配置文件 c ...

  2. mac 工作区

    https://www.zhihu.com/question/20917614 http://www.bjhee.com/mission-control.html 窗口切换 https://sspai ...

  3. [51nod1587]半现串

    将s所有长度为d/2的子串放进ac自动机中,直接匹配就可以判定半现串了再对其做一个差分,询问一个前缀的半现串个数,在ac自动机上数位dp,f[i][j][0/1]表示走了i步(i位的字符串),走到节点 ...

  4. [loj3364]植物比较

    结论:设$b_{i}$满足该限制,则$a_{i}$合法当且仅当$\forall i\ne j,a_{i}\ne a_{j}$且$\forall |i-j|<k,[a_{i}<a_{j}]= ...

  5. 保姆级神器 Maven,再也不用担心项目构建搞崩了

    今天来给大家介绍一款项目构建神器--Maven,不仅能帮我们自动化构建,还能够抽象构建过程,提供构建任务实现:它跨平台,对外提供了一致的操作接口,这一切足以使它成为优秀的.流行的构建工具,从此以后,再 ...

  6. 【k8s】在AWS EKS部署并通过ALB访问k8s Dashboard保姆级教程

    本教程适用范围 在AWS上使用EKS服务部署k8s Dashboard,并通过ALB访问 EKS集群计算节点采用托管EC2,并使用启动模板. 使用AWS海外账号,us-west-2区域 使用账号默认v ...

  7. 最简单的Python3启动浏览器代码

    #encoding=utf-8 from selenium import webdriver import time from time import sleep   dr = webdriver.F ...

  8. Orika - 类复制工具

    Orika 前言 类复制工具有很多,比较常用的有 mapstruct.Spring BeanUtils.Apache BeanUtils.dozer 等,目前我所在的项目组中使用的是 mapstruc ...

  9. Codeforces 1373F - Network Coverage(模拟网络流)

    Codeforces 题面传送门 & 洛谷题面传送门 提供一个模拟网络流的题解. 首先我们觉得这题一脸可以流的样子,稍微想想可以想到如下建图模型: 建立源点 \(S,T\) 和上下两排点,不妨 ...

  10. Codeforces 1422F - Boring Queries(树套树)

    upd on 2021.9.5:昨天的那个版本被 2-tower 卡爆了,故今天重发一个. Codeforces 题面传送门 & 洛谷题面传送门 没往"每个数最多只有一个 \(> ...