JAVA实现Excel批量导入
一、模板下载:
先将模板放在项目WebRoot下的download文件夹下:
/**
* @Title: downloadFile
* @Description: 模板下载 (网络地址)
* @param @param id
* @param @param url
* @param @param fileName
* @param @param response
* @param @param request
* @param @throws Exception
* @return void
* @throws
*/
@RequestMapping(value = "/downloadFile")
public void downloadFile(String url, String fileName,
HttpServletResponse response,HttpServletRequest request) throws Exception{ //要对文件名称进行编码
fileName = java.net.URLEncoder.encode(fileName,"utf-8");
response.addHeader("Content-Disposition","attachment;filename=" + fileName+";filename*=utf-8''"+fileName);
response.setContentType("application/octet-stream"); //设置文件MIME类型 OutputStream out =null;
InputStream in=null; //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载
//String path = request.getServletContext().getRealPath("/");
//url = path + "download\\" + "我的客户导入模板.xls"; try { URL urlPath = new URL(url);// 创建URL对象
in = urlPath.openStream();// 获取url中的输入流
out = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(out); byte[] buff = new byte[20480];
int b = 0;
while (-1 != (b = bis.read(buff))) {
bos.write(buff, 0, b);
}
bis.close();
bos.flush();
bos.close();
}catch(Exception e){
e.printStackTrace();
} finally {
if(out!=null)out.close();
if(in!=null)in.close();
}
}
/**
*
* @Title: download
* @Description: 下载本地文件
* @param @param path
* @param @param response
* @param @param request
* @return void
* @throws
*/
@RequestMapping(value = "/download")
public void download(String type, HttpServletResponse response, HttpServletRequest request) { User u = getUser(request.getSession());//SessionUtils.getUser(request.getSession()); //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载
//path = request.getServletContext().getRealPath("/") + "download\\" + "我的客户导入模板.xls";
String path = request.getServletContext().getRealPath("/"); List<BasedataResp> list1 = null;
List<BasedataResp> list2 = null;
QueryBasedataParam param1 = new QueryBasedataParam();
QueryBasedataParam param2 = new QueryBasedataParam();
param1.setCorpId(Long.valueOf(u.getCorpId()));
param2.setCorpId(Long.valueOf(u.getCorpId())); String fileName = "";
if("1".equals(type)){ fileName = "我的客户导入模板";
param1.setLabel("custom_status"); //客户状态
param2.setLabel("custom_level"); //客户分级
} else if("2".equals(type)){ fileName = "客户关联联系人导入模板";
param1.setLabel("contacts_role"); //角色关系
param2.setLabel("contacts_relation"); //亲密程度
}
String url = path + "download\\" + fileName + ".xls"; try { if(param1.getLabel()!=null && !"".equals(param1.getLabel())){
list1 = basedataService.selectBasedataInfo(param1); //查询系统标签
list2 = basedataService.selectBasedataInfo(param2); //查询系统标签
write(url, list1, list2);
}
ExcelExportUtil.getExcel(url, fileName, response); //下载sheet } catch (Exception e) {
System.out.println(e.getMessage());
}
} /**
*
* @Title: write
* @Description: 向已存在的Excel写入数据
* @param @param file
* @param @param list
* @param @param list2
* @param @return
* @return String
* @throws
*/
private String write(String file, List<BasedataResp> list, List<BasedataResp> list2) { try { FileInputStream fs = new FileInputStream(file); //获取已有的Excel
POIFSFileSystem ps = new POIFSFileSystem(fs); //使用POI提供的方法得到excel的信息
HSSFWorkbook wb = new HSSFWorkbook(ps);
HSSFSheet sheet1 = wb.getSheetAt(0); //获取第一个工作表,一个excel可能有多个工作表
HSSFSheet sheet2 = wb.getSheetAt(1); //获取第二个sheet
HSSFSheet sheet3 = wb.getSheetAt(2); //获取第三个sheet sheet2.removeRow(sheet2.getRow(0));
sheet3.removeRow(sheet3.getRow(0)); FileOutputStream out = new FileOutputStream(file); //向d://test.xls中写数据 HSSFRow row;
//向第二个sheet写入数据(第一个sheet中的下拉选项)
for (int i = 0; i < list.size(); i++) {
row = sheet2.createRow((short)(i)); //创建行
row.createCell(0).setCellValue(list.get(i).getName()); //设置第一个(从0开始)单元格的数据
}
//向第三个sheet写入数据(第一个sheet中的下拉选项)
HSSFRow row2;
for (int i = 0; i < list2.size(); i++) {
row2 = sheet3.createRow((short)(i)); //创建行
row2.createCell(0).setCellValue(list2.get(i).getName()); //设置第一个(从0开始)单元格的数据
} out.flush();
wb.write(out);
out.close(); } catch (Exception e) {
System.out.println(e.getMessage());
} return "success";
}
/**
*
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
* @param @param url 文件路径
* @param @param fileName 文件名
* @param @param response
* @return void
* @throws
*/
public static void getExcel(String url, String fileName, HttpServletResponse response){ try { //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data"); //2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls"); //支持中文文件名 //通过文件路径获得File对象
File file = new File(url); FileInputStream in = new FileInputStream(file);
//3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream()); int b = 0;
byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){
out.write(buffer,0,b); //4.写到输出流(out)中
} in.close();
out.flush();
out.close(); } catch (IOException e) {
e.printStackTrace();
}
}
模板截图:

二、通过Excel模板导入数据:
/**
*
* @Title: impExcel
* @Description: 批量导入客户信息
* @param @param request
* @param @param response
* @param @return
* @return String
* @throws
*/
@RequestMapping("impExcel")
@ResponseBody
public String impExcel(MultipartHttpServletRequest request,HttpServletResponse response){ ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CustomConstants.CUSTOM_SELECT_EXCEPTION,"导入客户信息失败",null); MultipartFile file = request.getFile("file");
ExcelReader er = new ExcelReader();
int count =0;
int error =0;
int success = 0; List<Custom> list_ = new ArrayList<Custom>();
User u = getUser(request.getSession());//SessionUtils.getUser(request.getSession());
Long corpId = Long.valueOf(u.getCorpId());
Date date = new Date();
String returnMsg = "";
int index = 1; try { List<Map<Integer,String>> list = er.readExcelContentByList(file.getInputStream()); //读取Excel数据内容
count = list.size(); for(Map<Integer,String> map : list){ if(map.get(0)==null || "".equals(map.get(0))){
returnMsg += "第"+index+"行:【客户简称(必填)】列不能为空;";
} else if(map.get(1)==null || "".equals(map.get(1))){
returnMsg += "第"+index+"行:【客户全称(必填)】列不能为空;";
} else {
int num = 0;
QueryCustomParam params = new QueryCustomParam();
params.setShortName(map.get(0));
params.setCorpId(Long.valueOf(u.getCorpId()));
num = customService.checkCustom(params); //查询相同客户 if(num==0){
Custom custom = new Custom();
custom.setId(UUIDUtil.getLongUUID());
custom.setShortName(map.get(0)==null? null : map.get(0));
custom.setName(map.get(1)==null? null : map.get(1));
custom.setNumber(map.get(2)==null? null : map.get(2));
custom.setAddress(map.get(3)==null? null : map.get(3));
custom.setUrl(map.get(4)==null? null : map.get(4));
custom.setDescription(map.get(5)==null? null : map.get(5));
custom.setCustomStatusId(map.get(6)==null? null : basedataService.getLabelId("custom_status", map.get(6), corpId) );
custom.setCustomLevelId(map.get(7)==null? null : basedataService.getLabelId("custom_level", map.get(7), corpId) );
custom.setCreaterId(Long.valueOf(u.getUserId()));
custom.setCreateDate(date);
custom.setUpdaterId(Long.valueOf(u.getUserId()));
custom.setUpdateDate(date);
custom.setCorpId(Long.valueOf(u.getCorpId())); list_.add(custom); } else {
returnMsg += "第"+index+"行:【客户简称(必填)】列:"+ map.get(0)+"已存在;";
}
index++;
}
} int cuccess = customService.batchInsert(list_); //批量导入客户信息 standardData.setReturnCode(0);
standardData.setReturnData(null); error = count - success;
standardData.setReturnMessage(returnMsg); } catch (Exception e) {
log.error("批量导入客户信息异常:" + e.getMessage());
standardData.setReturnMessage(e.getMessage());
} return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
}
读取Excel内容工具类:
/**
* 读取Excel数据内容
* @param InputStream
* @return List<Map<String, String>> Map的key是列Id(0代表第一列),值是具体内容
*/
public List<Map<Integer, String>> readExcelContentByList(InputStream is) { List<Map<Integer, String>> list = new ArrayList<Map<Integer,String>>(); try {
//fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(is);
//wb = new XSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
} sheet = wb.getSheetAt(0); // 得到总行数
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells(); // 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer,String> map = new HashMap<Integer, String>(); while (j < colNum) {
// 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
// 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-"; map.put(j, getCellFormatValue(row.getCell((short) j)).trim().replaceAll("\t\r", ""));
//str += getCellFormatValue(row.getCell((short) j)).trim() + " ";
j++;
}
list.add(map);
}
return list;
}
JAVA实现Excel批量导入的更多相关文章
- 订餐系统之Excel批量导入
		
批量导入现在基本已经成为各类系统的标配了,当前,我们订餐系统也不例外,什么商家呀.商品呀.优惠码之类的,都少不了.毕竟嘛,对非开发人员来说,看到Excel肯定比看到很多管理系统还是要亲切很多的.这里, ...
 - java实现excel的导入导出(poi详解)[转]
		
java实现excel的导入导出(poi详解) 博客分类: java技术 excel导出poijava 经过两天的研究,现在对excel导出有点心得了.我们使用的excel导出的jar包是poi这个 ...
 - Excel批量导入商品,遇到导入失败记录到另一个Excel中供下载查看
		
/// <summary> /// EXCEL批量导入 /// </summary> /// <param name="filePath">文件 ...
 - zabbix3.4用Python脚本Excel批量导入主机
		
1.安装xlrd读取Excel文件 1.1. 下载setuptools-38.2.4.zip,上传至zabbix服务器解压安装,下载地址:https://pypi.python.org/package ...
 - Java实现数据批量导入mysql数据库
		
本文完全照搬别人的. 原文标题:Java实现数据批量导入数据库(优化速度-2种方法) 原文地址:https://blog.csdn.net/qy20115549/article/details/526 ...
 - java使用POI实现Excel批量导入数据
		
1.准备工作 1.1 创建模板表头与数据库表字段一一对应,示例如下 1.2将模板放入项目中,如下图所示: 2.前端页面 2.1 使用超链接提供模板下载地址 <html lang="zh ...
 - java实现文件批量导入导出实例(兼容xls,xlsx)
		
1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...
 - java 中Excel的导入导出
		
部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字 的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...
 - JAVA对Excel的导入导出
		
今天需要对比2个excel表的内容找出相同:由于要学的还很多上手很慢所以在这做个分享希望对初学的有帮助: 先是pom的配置: <dependency> <groupId>org ...
 
随机推荐
- 用Micro:bit做床头灯
			
这是一个非常简单的项目,给孩子们介绍感应和控制,使用光敏电阻LDR作为光线传感器和床头灯的LED. 这也介绍了模拟输入的概念.数字输入为ON或OFF.只有0和1两种可能的条件.仿真输入是一系列可能值中 ...
 - Python3实现机器学习经典算法(二)KNN实现简单OCR
			
一.前言 1.ocr概述 OCR (Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗.亮的模式确定其形状,然 ...
 - Python mutilprocessing Processing 父子进程共享文件对象?
			
multiprocessing python多进程模块, 于是, Processing也是多进程的宠儿. 但今天讨论的问题, 似乎也能引起我们一番重视 直接上代码: 1 2 3 4 5 6 7 ...
 - oracle时间转换查询
			
查询oracle 数据库时要查询某一字段的最大时间或者最小时间,因为oracle的时间点 精确到毫秒 甚至更高精度级别 根据字段来转换成对应的时间格式: SELECT TO_CHAR(MAX(crea ...
 - ASP.NET MVC5 学习系列之模型绑定
			
一.理解 Model Binding Model Binding(模型绑定) 是 HTTP 请求和 Action 方法之间的桥梁,它根据 Action 方法中的 Model 类型创建 .NET 对象, ...
 - 团队Alpha冲刺(十)
			
目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...
 - lintcode-414-两个整数相除
			
414-两个整数相除 将两个整数相除,要求不使用乘法.除法和 mod 运算符. 如果溢出,返回 2147483647 . 样例 给定被除数 = 100 ,除数 = 9,返回 11. 标签 二分法 思路 ...
 - 简述Java中Http/Https请求监听方法
			
一.工欲善其事必先利其器 做Web开发的人总免不了与Http/Https请求打交道,很多时候我们都希望能够直观的的看到我们发送的请求参数和服务器返回的响应信息,这个时候就需要借助于某些工具啦.本文将采 ...
 - 在原有的基础之上,启用NAT模型
			
# 给虚拟主机实例添加一个网关 route add default gw 192.168.23.1 # 在宿主机打开网卡间转发功能 echo 1 > /proc/sys/net/ipv4/i ...
 - crontab笔记
			
* * * * * root rm -f /var/spool/cron/lastrun/cron.hourly > out.file 第一部分:执行的周期与时间 ...