java的EXcel模板的下载、导⼊和导出
声明:本⽂章仅基于个⼈粗略整理总结,如有不⾜之处,欢迎指出。
基于ssm+layui开发,所需jar包
<!-- poi3.9:导出excel -->
<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>
1、下载Excel模板
前端:
<div class="layui-form-item"></div>
<form action="/device/downloadExcel" method="get">pwn渗透
<div class="layui-form-item">
<label class="layui-form-label">下载模板:</label>
<div class="layui-input-inline">
<input class="layui-btn " type="submit" value="下载模板">
</div>
</form>
<label class="layui-form-label"></label>
<!-- -->
<form class="layui-form" method="POST" enctype="multipart/form-data"
id="form1" action="${ctx}/device/uploadExcel">
<div class="layui-form-item">
<label class="layui-form-label">上传⽂件:</label>
<div class="layui-input-inline">
<input id="upfile" type="file" name="upfile" calss="layui-btn">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"> </label>
<div class="layui-input-inline">
<input class="layui-btn " type="submit" value="批量导⼊Excel数据"
onclick="return checkData()">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">注意事项:</label>
<div class="layui-input-block">
<span ></br>1、请根据模板填写数据。</br>2、⾮必填列不要删除。</br>3、不要调整各个列的先后顺序。</span> </div>
</div>
</form>
</body>
<script type="text/javascript" src="${ctx }/layui/layui.js"></script>
<script language="javascript">
base : "js/"
}).use(['form','layer','jquery','laydate'],function(){
var form = layui.form,
layer = parent.layer === undefined ? layui.layer : parent.layer,laydate = layui.laydate
layer = parent.layer === undefined ? layui.layer : parent.layer,laydate = layui.laydate $ = layui.jquery;
});
//JS校验form表单信息
function checkData() {
var fileDir = $("#upfile").val();
var suffix = fileDir.substr(fileDir.lastIndexOf("."));
if ("" == fileDir) {
top.layer.msg("选择需要导⼊的Excel⽂件!", {
icon : 5
});
return false;
}
if (".xls" != suffix && ".xlsx" != suffix) {
top.layer.msg("⽂件格式有误!</br>选择Excel格式的⽂件导⼊!", {
icon : 5
});
return false;
}
汇编语言入门论坛$("#form1").attr('disabled','disabled');
var index = top.layer.msg('数据提交中,请稍候', {
icon : 16,
shade : 1
});
$('#form1').ajaxSubmit({
url : ctx + '/device/uploadExcel',
dataType:'text',//服务器返回的数据类型可选XML ,Json jsonp script html text等
error:function(){
$("#form1").removeAttr('disabled');
top.layer.msg("导⼊excel出错!", {
icon : 5
});
},
success:function(d){
/
/alert(d);
top.layer.msg(d, {icon : 1
});
$("#upfile").val("");
$("#form1").removeAttr('disabled');
//刷新⽗页⾯
//load();
}
}); //form1
return true;
}
</script>
后端:
模板⽂件存放位置:
代码:
@RequestMapping(value="downloadExcel", method = RequestMethod.GET)//method = RequestMethod.GET将数据传递给前端
public void downloadExcel(HttpServletResponse response,HttpServletRequest request)throws IOException {
//获取输⼊流,原始模板位置
String filePath = getClass().getResource("/resource/template/xx模板.xlsx" ).getPath();
InputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
//假如以中⽂名下载的话,设置下载⽂件名称
String filename = "导⼊模板.xls";
//转码,免得⽂件名中⽂乱码
filename = de(filename,"UTF-8");
//设置⽂件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置⽂件ContentType类型,这样设置,会⾃动判断下载⽂件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new OutputStream());
int len = 0;
while((len = ad()) != -1){
out.write(len);
out.flush();
}
out.close();
}
2、导⼊数据
controller
@RequestMapping(value = "uploadExcel",method = { RequestMethod.GET , RequestMethod.POST} )
@ResponseBody
public ResponseEntity<String> ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException { String commentHTML=null;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(new MediaType("text","html",Charset.forName("UTF-8")));
try {
commentHTML = deviceService.importDeviceExcel(request, response);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (StringUtils.isNotBlank(commentHTML)) {
return new ResponseEntity<String>(commentHTML, responseHeaders, HttpStatus.OK);
}else {
return new ResponseEntity<String>("导⼊失败!", responseHeaders, HttpStatus.OK);
}
}
Service:
private String no="0";//excel⾥的序号
public String importDeviceExcel(HttpServletRequest request, HttpServletResponse response)throws Exception{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
InputStream in = null;
List<List<String>> listob = null;
MultipartFile file = File("upfile");
if (file.isEmpty()) {
throw new Exception("⽂件不存在!");
}
in = InputStream();
listob = BankListByExcel(in, OriginalFilename());
in.close();
int successCount=0;
int failCount=0;
/
/导⼊字段条件判断
ArrayList<ArrayList<String>> fieldData =new ArrayList<ArrayList<String>>();//必填值为空的数据⾏
Device device = new Device();//格式⽆误的数据⾏
int lisize=listob.size();
for (int i = 0; i < lisize; i++) {//这部分for循环可根据需求选择忽视
List<String> lo = (i);
if (!no.(0))) {//no为EXCEL的序列号,本例中excel的第⼀⾏是各列的标题,不导⼊,从第⼆⾏开始
(0);
if (StringUtils.(1))){//判断每⾏某个数据是否符合规范要求
//符合要求,插⼊到数据库Device表中
saveDeviceFromExcel(device,lo);
lo=null;
successCount+=1;
}else{
//需要另外⽣成excel的不规范⾏,构造excel的数据
ArrayList<String> dataString=new ArrayList<String>();
for(int j=0;j<lo.size();j++){
String a=String.(j));
dataString.add(a);
}
fieldData.add(dataString);
}
}
}
failCount=fieldData.size();
String o=null;
if (failCount>0) {
//不符合规范的重新⽣成EXCEL表
insExcel(fieldData,response);
如何快速结束任务进程o="成功导⼊"+successCount+"⾏,未成功导⼊"+failCount+"⾏,请在有误数据表内查看!";
}else{
//o="全部导⼊成功!";
}
no="0";
return o;
二级建造师考试科目}
public void insExcel( ArrayList<ArrayList<String>> fieldData,HttpServletResponse response) throws Exception{
if(fieldData!=null&&fieldData.size()>0){//如果存在不规范⾏,则重新⽣成表
//使⽤ExcelFileGenerator完成导出
LoadExcelUtil loadExcelUtil = new LoadExcelUtil(fieldData);
OutputStream os = OutputStream();
//导出excel建议加上重置输出流,可以不加该代码,但是如果不加必须要保证输出流中不应该在存在其他数据,否则导出会有问题 set();
//配置://⽂件名
//配置://⽂件名
String fileName = "有误数据表("+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+").xls";
//处理乱码
fileName = new Bytes("gbk"),"iso-8859-1");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename="+fileName);
response.setBufferSize(1024);
//导出excel的操作
}
}
导⼊时读取EXCEL⼯具类
基本思路:
将list集合的中的数据导⼊到excel表中的步骤如下:
1、创建 WorkBook对象
2、获取要导出的表格的总记录数
3、根据总记录和每个excels的所容纳的记录数,进⾏分页处理,得出分为⼏个sheet的excels
4、得出sheet,进⾏每个sheet的循环处理
4.1、通过workbook对象进⾏创建createSheet,HSSFSheet对象
4.2、拥有了HSSFSheet对象,创建ateRow⾏表头,单独的⼀⾏即数据说明
4.3、创建表头⾏HSSFRow,开始导⼊表头⾏数据,开始对表头这⼀⾏进⾏数据循环填充
4.4、接着开始循环每⼀⾏数据,对总记录进⾏循环,如果超过最⼤容量,那么最⼤值就是它,否则就
是实际记录数 4.5、开始进⼊循环,然后都要创建⼀个⾏对象HSSFRow,根据现在的页数取出第⼏条数据集合,进⾏循环
4.5.1、也是通过HSSFRow,创建HSSFCell列对象
4.5.2、通过cell对象设置相应的样式或者编码
jquery下载文件请求4.5.3、编码设置完,就可以进⾏每列数据的填充
5、返回workBook对象
package com.irs.util;
import java.io.IOException;
import java.io.InputStream;
DecimalFormat;
SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @ClassName: ImportExcelUtil
* @Description: excel数据导⼊数据库
* @Author:
* @Version: V1.00 (版本号)
* @CreateDate:
*/
public class ImportExcelUtil {
private final static String excel2003L = ".xls"; // 2003- 版本的excel
private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论