版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第Java实现批量导出导入数据及附件文件zip包目录前言-应用场景一、导出ZIP包1.列表数据导出到本地excel文件2.下载附件信息3.生成压缩文件(浏览器下载)4.删除临时目录二、导入ZIP包1.上传zip包,解压到临时目录2.读取附件信息上传到文件服务器3.读取Excel文件存入数据库4.删除临时文件
前言-应用场景
某系统在不同单位使用时存在两套生产环境,他们的数据不是互通的,所以这些单位的上一级领导部门在统计数据的时候希望将A系统的数据和附件信息导出到一个压缩包里,然后把这个压缩包一键导入到B系统,这样B系统就包含了全部的数据,上级领导就能看到全部的业务信息,便于统计分析。
一、导出ZIP包
1.列表数据导出到本地excel文件
Stringpath=profile+"/temp/"+DateUtils.dateTimeNow();
Filefile=newFile(path);
if(file.mkdirs()){
System.out.println("文件夹创建成功!创建后的文件目录为:"+file.getPath());
//1.输出Excel文件
HSSFWorkbookworkbook=newHSSFWorkbook();
HSSFSheetsheet=workbook.createSheet("sheet");
StringfileName="XX数据导出.xls";
StringsavePath=file.getPath()+File.separator+fileName;
OutputStreamos=newFileOutputStream(savePath);
//响应到客户端(即浏览器端直接弹出下载连接的方式)需要用response获取流
//this.setResponseHeader(response,filename);
//OutputStreamos=response.getOutputStream();
ListHashMapdataList=newArrayList();
try{
//表头
this.createExcelTitle(workbook,sheet);
//查询条件
HashMapparam=this.buildQueryParams(params);
dataList=shareRegisterMapper.shareList(param);
if(CollectionUtils.isEmpty(dataList)){
return;
this.dealAssetData(dataList,sheet);
//处理子表数据
this.dealAssetDetailData(dataList,workbook);
workbook.write(os);
os.flush();
os.close();
}catch(Exceptione){
e.printStackTrace();
}finally{
if(os!=null){
os.flush();
os.close();
workbook.close();
}
2.下载附件信息
在上一步生成的Excel文件路径下新建files文件夹,里面存放附件
publicvoiddownloadFile(ListHashMapdataList)throwsException{
StringurlPrefix=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
StringsavePath=file.getPath()+File.separator+"/files";
OutputStreamos=null;
InputStreamis=null;
inti=0;
try{
for(HashMapdata:dataList){
if(data==null||data.get("FILES")==null){
continue;
ListZsglFileEntityentityList=newArrayList();
String[]fileArray=data.get("FILES").toString().split(",");
ListidList=Arrays.asList(fileArray);
entityList.addAll(fileMapper.selectByIds(idList));
if(CollectionUtils.isNotEmpty(entityList)){
for(ZsglFileEntityfile:entityList){
if(file.getFssFileId()==null){
continue;
StringfileUrl=urlPrefix+"/fss/download/"+file.getFssFileId();
//构造URL
URLurl=newURL(fileUrl);
//打开连接
URLConnectioncon=url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
//输入流
is=con.getInputStream();
FiletempFile=newFile(savePath+"/"+file.getFileName());
//校验文件夹目录是否存在,不存在就创建一个目录
if(!tempFile.getParentFile().exists()){
tempFile.getParentFile().mkdirs();
os=newFileOutputStream(tempFile);
is=con.getInputStream();
con.getHeaderFields();
IOUtils.copy(is,os);
System.out.println("下载完成");
entityList.clear();
}catch(IOExceptione){
System.err.println(e);
}finally{
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
3.生成压缩文件(浏览器下载)
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("content-disposition","attachment;filename="+"XX数据导出.zip");
ZipOutputStreamzos=newZipOutputStream(response.getOutputStream());
try{
File[]sourceFiles=file.listFiles();
if(null==sourceFiles||sourceFiles.length1){
System.out.println("待压缩的文件目录:"+"里面不存在文件,无需压缩.");
}else{
for(inti=0;isourceFiles.length;i++){
FilesrcFile=sourceFiles[i];
if(srcFile.isDirectory()){
File[]imageSourceFiles=srcFile.listFiles();
if(null==imageSourceFiles||imageSourceFiles.length1){
continue;
for(FileimageFile:imageSourceFiles){
compress(zos,imageFile,srcFile.getName()+"/");
}else{
compress(zos,srcFile,"");
}catch(Exceptione){
e.printStackTrace();
}finally{
//关闭流
try{
if(null!=zos){
zos.close();
}catch(IOExceptione){
e.printStackTrace();
}
其中的压缩方法如下:
publicvoidcompress(ZipOutputStreamout,FilesourceFile,Stringbase)throwsException
out.putNextEntry(newZipEntry(base+sourceFile.getName()));
FileInputStreamfos=newFileInputStream(sourceFile);
BufferedInputStreambis=newBufferedInputStream(fos);
inttag;
System.out.println(base);
//将源文件写入到zip文件中
while((tag=bis.read())!=-1){
out.write(tag);
out.flush();
out.closeEntry();
bis.close();
fos.close();
}
4.删除临时目录
publicvoiddeleteDirectory(Filefile){
File[]list=file.listFiles();//无法做到list多层文件夹数据
if(list!=null){
for(Filetemp:list){//先去递归删除子文件夹及子文件
deleteDirectory(temp);//注意这里是递归调用
if(!file.delete()){//再删除自己本身的文件夹
logger.error("文件删除失败:%s%n",file);
二、导入ZIP包
1.上传zip包,解压到临时目录
这里开始想着在不解压的情况下读取里面的文件,结果没有走通。因为zip里面包含了子文件夹里面的附件信息需要解析。不解压直接解析文件适用于只需要解析zip包中第一层文件的场景,如果子文件夹下的文件也需要处理的话,最好解压后再处理。
publicvoidunzip(ZipInputStreamzipIn,StringdestDirectory)throwsIOException{
FiledestDir=newFile(destDirectory);
if(!destDir.exists()){
destDir.mkdirs();
ZipEntryentry=zipIn.getNextEntry();
//遍历Zip文件中的条目
while(entry!=null){
StringfilePath=destDirectory+File.separator+entry.getName();
if(!entry.isDirectory()){
intindex=entry.getName().indexOf("/");
if(index-1entry.getName().length()index){
FiletempFile=newFile(destDirectory+File.separator+entry.getName().substring(0,index));
if(!tempFile.exists()){
tempFile.mkdir();
FilecheckFile=newFile(filePath);
if(!checkFile.exists()){
checkFile.createNewFile();//创建目标文件
//如果条目是文件直接解压
BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(filePath));
byte[]bytesIn=newbyte[1024];
intread=0;
while((read=zipIn.read(bytesIn))!=-1){
bos.write(bytesIn,0,read);
bos.close();
}else{
Filedir=newFile(filePath);
if(!dir.exists()){
dir.mkdirs();
zipIn.closeEntry();
entry=zipIn.getNextEntry();
zipIn.close();
}
这里解压遇到了一个问题,之前导出生成的zip包直接导入没问题,但是我把导出的包手动解压后修改了部分数据重新压缩后再导入报错:ZipInputStream解压远程文件报错,java.lang.IllegalArgumentException:MALFORMED
原因:文件名含有中文,zip解析出错
解决方案,如下行代码,在生成ZipInputStream的时候指定编码格式。
ZipInputStreamzis=newZipInputStream(newBufferedInputStream(inputStream),Charset.forName(GBK));
2.读取附件信息上传到文件服务器
publicListHashMapreadLocalFile()throwsException{
Filefile=newFile(destDirectory+"/files");
ListHashMapfssList=newArrayList();
if(file.exists()){
File[]sourceFiles=file.listFiles();
if(null==sourceFiles||sourceFiles.length1){
System.out.println(file.getName()+"目录里面不存在文件,无需处理.");
returnfssList;
}else{
for(inti=0;isourceFiles.length;i++){
FilesrcFile=sourceFiles[i];
FileItemFactoryfactory=newDiskFileItemFactory(16,null);
FileItemitem=factory.createItem(srcFile.getName(),"text/plain",true,srcFile.getName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
try{
FileInputStreamfis=newFileInputStream(srcFile);
OutputStreamos=item.getOutputStream();
while((bytesRead=fis.read(buffer,0,8192))!=-1){
os.write(buffer,0,bytesRead);
os.close();
fis.close();
}catch(IOException
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- GB/T 3903.24-2026鞋类鞋跟试验方法持钉力
- 幼儿园教师专业学习共同体运行效能研究-基于教研活动记录与教师成长数据
- 美育基础概述 9
- 建筑项目策划
- 会议系统施工方案
- 智能化工程施工操作规程
- 焦虑自评量表(SAS)修订版
- 平面设计工设备清单
- 2025高考四川卷生物真题试卷(纯答案版)
- 5G工业互联网智能装备生产基地建设项目可行性研究报告模板拿地申报
- 生物浙江宁波市三锋联盟2025-2026学年度高一年级第二(下)学期期中联考(4.22-4.24)
- 2026年二级建造师二建法规考前预测重点知识强化记忆总结笔记
- 2026云南省有色地质局楚雄勘查院下属企业招聘工作人员11人笔试备考试题及答案解析
- 心血管科试卷及分析
- 2026四川发展(控股)有限责任公司所属公司招聘5人笔试参考题库及答案解析
- 湖北省武汉市2026届高三毕业生四月调研考试语文试卷(含答案)
- 养老机构防灾避险课件
- 2026年辽宁能源集团招聘考试指南及模拟题解析
- 2026广东广州市黄埔区大沙街道招聘编外聘用人员4人备考题库及参考答案详解
- 国家事业单位招聘2025中国工艺美术馆招聘拟聘人员笔试历年参考题库典型考点附带答案详解(3卷合一)
- 企业管理 华为会议接待全流程手册SOP
评论
0/150
提交评论