导入

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. [jmeter]Jmeter+ant实现接口自动化

    1.安装jmeter 和ant &环境变量配置百度去~ 2.jmeter和ant关联 &将JMeter所在目录下extras子目录里的ant-JMeter-1.1.1.jar复制到an ...

  2. 使用Adobe Acrobat进行Word转PDF遇到的问题及解决方法

    软件版本:Adobe Acrobat 9 Pro 使用场景:Word转PDF 问题1: 我以为先要在Adobe Acrobat 9 Pro中打开Word文件,然后在执行类似转换/导出操作.但是始终无法 ...

  3. newInstance方法

    1.new 是java中的关键字,是创建一个新对象的关键字.用new这个关键字的话,是调用new指令创建一个对象,然后调用构造方法来初始化这个对象,如果反编译class的话,会看到一个Object o ...

  4. C# 计算农历日期方法(2021版)

    解决问题 旧版农历获取方法报错,会有 到 2021年 m数组越界了 if (LunarData[m] < 4095) 此方法可以解决 主体代码 public static class China ...

  5. Java核心技术--Java程序设计

    Java术语 术语名 缩写 解释 Java Development Kit(Java开发工具包) JDK 编写Java程序的程序员使用的软件 Java Runtime Environment(Java ...

  6. [hdu7082]Pty loves lcm

    先将问题差分,即仅考虑上限$R$(和$L-1$) 注意到$f(x,y)$增长是较快的,对其分类讨论: 1.若$y\ge x+2$,此时满足$f(x,y)\le 10^{18}$的$(x,y)$只有约$ ...

  7. [luogu5294]序列

    也是一道保序回归的题,但思路不同于论文中模板题 考虑两个开口向上的二次函数$f(x)$和$g(x)$,求任意实数$x,y$满足$x\le y$且最小化$f(x)+g(y)$,这个最小值可以分类讨论求出 ...

  8. 实用QPS和TPS高的高效分析方法

    现在主库的MySQL的QPS一直在3K/s左右,想知道其到底执行了那些SQL,或者是那些SQL执行的次数比较多: 腾讯云的后台监控: 开启腾讯云的SQL审计后,下载几分钟SQL日志文件, 下列语句在M ...

  9. 查找 Search

    如果值域小一点. 那么我们有一个很精妙的做法. 分块完维护数字\(cnt\),和一个\(bitset\)信息. 然而小不得. 那么我们考虑维护后缀\(nxt_i\),表示第\(i\)位后,最近的\(a ...

  10. 【Meta】16s rRNA和16s rDNA的区别

    在文章或宣传稿中经常看到两者滥用,实际上是不同的. 首先是各个字母的含义: 16S中的"S"是一个沉降系数,亦即反映生物大分子在离心场中向下沉降速度的一个指标,值越高,说明分子越大 ...