我是靠谱客的博主 飞快小蘑菇,最近开发中收集的这篇文章主要介绍Java根据excel/word模板进行值替换并且打成压缩包一 前端代码(MbTemplateList.vue)二 后端代码MbTemplateController.javaIMbTemplateService.javaMbTemplateServiceImpl.java提供了zip的压缩和解压的api提供删除文件夹下面内容的方法,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
目录
一 前端代码(MbTemplateList.vue)
二 后端代码
MbTemplateController.java
IMbTemplateService.java
MbTemplateServiceImpl.java
提供了zip的压缩和解压的api
提供删除文件夹下面内容的方法
一 前端代码(MbTemplateList.vue)
模板制作和文件夹创建
xlsx模板制作
docx模板制作
替换excel的依赖
<!--创建表的插件--> <dependency> <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> <artifactId>mybatis-enhance-actable</artifactId> <version>1.1.1.RELEASE</version> </dependency> <!--druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <!-- poi 相关 表中值替换 --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency>
替换word模板需要的依赖
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories>
*使用这个依赖会产生水印 <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>5.4.2</version> </dependency>#使用这个依赖不会产生水印
<dependency> <groupId> e-iceblue </groupId> <artifactId>spire.doc.free</artifactId> <version>5.2.0</version> </dependency>
文件夹创建
1 模板excel或者word文件存放位置
D:optupFilestemp
2 替换后的excel文件存放 (同样也是打包的文件夹)-----自己随便创建一个
D:optwd
<template>
<a-card :bordered="false">
<!-- 查询区域 -->
<div class="table-page-search-wrapper">
<a-form layout="inline"
@keyup.enter.native="searchQuery">
<a-row :gutter="24">
</a-row>
</a-form>
</div>
<!-- 查询区域-END -->
<div class="table-page-search-wrapper">
<a-form layout="inline"
@keyup.enter.native="searchQuery">
<a-row :gutter="24">
<a-col :md="4"
:sm="12">
<a-form-item label="姓名">
<j-input placeholder="输入姓名模糊查询"
v-model="queryParam.name"></j-input>
</a-form-item>
</a-col>
<a-col :md="5"
:sm="12">
<a-form-item label="身份证号">
<j-input placeholder="输入身份证查询"
v-model="queryParam.idCard"></j-input>
</a-form-item>
</a-col>
<a-col :md="5"
:sm="12">
<a-form-item label="联系电话">
<j-input placeholder="输入电话查询"
v-model="queryParam.phone"></j-input>
</a-form-item>
</a-col>
<a-col :md="6"
:sm="8">
<span style="float: left;overflow: hidden;"
class="table-page-search-submitButtons">
<a-button type="primary"
@click="searchQuery"
icon="search">搜索</a-button>
<a-button type="primary"
@click="searchReset"
icon="reload"
style="margin-left: 8px">重置</a-button>
</span>
</a-col>
</a-row>
</a-form>
</div>
<!-- 操作按钮区域 -->
<div class="table-operator">
<a-button @click="handleAdd"
type="primary"
icon="plus">新增贷款</a-button>
<a-upload name="file"
:showUploadList="false"
:multiple="false"
:headers="tokenHeader"
:action="importExcelUrl"
@change="handleImportExcel">
<a-button type="primary"
icon="import">导入贷款</a-button>
</a-upload>
<a-button type="primary"
icon="download"
@click="handleExportXls('个人贷款模板')">导出贷款</a-button>
<!-- 高级查询区域 -->
<!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
<a-dropdown v-if="selectedRowKeys.length > 0">
<a-menu slot="overlay">
<a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
</a-menu>
<a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
</a-dropdown> -->
</div>
<!-- table区域-begin -->
<div>
<div class="ant-alert ant-alert-info"
style="margin-bottom: 16px;">
<i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
<a style="margin-left: 24px"
@click="onClearSelected">清空</a>
</div>
<a-table ref="table"
size="middle"
:scroll="{x:true}"
bordered
rowKey="id"
:columns="columns"
:dataSource="dataSource"
:pagination="ipagination"
:loading="loading"
:rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
class="j-table-force-nowrap"
@change="handleTableChange">
<template slot="htmlSlot"
slot-scope="text">
<div v-html="text"></div>
</template>
<template slot="imgSlot"
slot-scope="text">
<span v-if="!text"
style="font-size: 12px;font-style: italic;">无图片</span>
<img v-else
:src="getImgView(text)"
height="25px"
alt=""
style="max-width:80px;font-size: 12px;font-style: italic;" />
</template>
<template slot="fileSlot"
slot-scope="text">
<span v-if="!text"
style="font-size: 12px;font-style: italic;">无文件</span>
<a-button v-else
:ghost="true"
type="primary"
icon="download"
size="small"
@click="downloadFile(text)">
下载
</a-button>
</template>
<span slot="action"
slot-scope="text, record">
<a @click="handleEdit(record)">编辑</a>
<a-divider type="vertical" />
<a @click="showModal(record)">下载文档</a>
<a-divider type="vertical" />
<a-popconfirm title="确定删除吗?"
@confirm="() => handleDelete(record.id)">
<a>删除</a>
</a-popconfirm>
</span>
</a-table>
</div>
<mb-template-modal ref="modalForm"
@ok="modalFormOk"></mb-template-modal>
<j-modal title="选择文档"
:width="800"
:visible="docVisible"
switchFullscreen
@ok="handlePrint"
@cancel="docVisible = false"
cancelText="关闭">
<a-checkbox-group @change="onChange"
style="width: 100%">
<div class="check-box"
v-for="(items, index) in docList"
:key="index">
<div class="label" v-if="items.children.length > 0">{{items.label}}</div>
<a-row>
<a-col :span="8"
v-for="(item, i) in items.children"
:key="i">
<a-checkbox :value="item.id">
{{item.name}}
</a-checkbox>
</a-col>
</a-row>
</div>
</a-checkbox-group>
</j-modal>
</a-card>
</template>
<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import MbTemplateModal from './modules/MbTemplateModal'
import { filterDictTextByCache, initDictOptions } from '@/components/dict/JDictSelectUtil'
import { getAction, downFile } from '@/api/manage'
export default {
name: 'MbTemplateList',
mixins: [JeecgListMixin, mixinDevice],
components: {
MbTemplateModal,
},
data() {
return {
description: '个人贷款模板管理页面',
// 表头
columns: [
{
title: '添加时间',
align: "center",
dataIndex: 'createTime'
},
{
title: '姓名',
align: "center",
dataIndex: 'name'
},
{
title: '身份证号码',
align: "center",
dataIndex: 'idCard'
},
{
title: '地址',
align: "center",
dataIndex: 'adder'
},
{
title: '电话',
align: "center",
dataIndex: 'phone'
},
{
title: '借款金额-(万)',
align: "center",
dataIndex: 'loanAmount'
},
{
title: '借款期限-(月)',
align: "center",
dataIndex: 'loanTerm'
},
{
title: '网点',
align: "center",
dataIndex: 'network'
},
{
title: '客户经理',
align: "center",
dataIndex: 'accountManager'
},
{
title: '状态',
align: "center",
dataIndex: 'status',
customRender: (text) => {
//字典值替换通用方法
return filterDictTextByCache('me_status', text);
}
},
{
title: '操作',
dataIndex: 'action',
align: "center",
fixed: "right",
width: 147,
scopedSlots: { customRender: 'action' }
}
],
url: {
list: "/mbTemplate/list",
delete: "/mbTemplate/delete",
deleteBatch: "/mbTemplate/deleteBatch",
exportXlsUrl: "/mbTemplate/exportXls",
importExcelUrl: "/mbTemplate/importExcel",
},
dictOptions: {},
superFieldList: [],
docVisible: false,
docList: [],
statusList: [],
checkList: [],
recordObj: {},
}
},
created() {
this.getSuperFieldList();
this.getStatusList();
},
computed: {
importExcelUrl: function () {
return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
},
},
methods: {
initDictConfig() {
},
getSuperFieldList() {
let fieldList = [];
fieldList.push({ type: 'string', value: 'name', text: '姓名', dictCode: '' })
fieldList.push({ type: 'string', value: 'sex', text: '性别', dictCode: '' })
fieldList.push({ type: 'string', value: 'age', text: '年龄', dictCode: '' })
fieldList.push({ type: 'string', value: 'idCard', text: '身份证号码', dictCode: '' })
fieldList.push({ type: 'string', value: 'adder', text: '地址', dictCode: '' })
fieldList.push({ type: 'string', value: 'phone', text: '电话', dictCode: '' })
fieldList.push({ type: 'BigDecimal', value: 'loanAmount', text: '借款金额', dictCode: '' })
fieldList.push({ type: 'string', value: 'loanTerm', text: '借款期限', dictCode: '' })
fieldList.push({ type: 'string', value: 'network', text: '网点', dictCode: '' })
fieldList.push({ type: 'string', value: 'accountManager', text: '客户经理', dictCode: '' })
fieldList.push({ type: 'string', value: 'status', text: '状态', dictCode: '' })
this.superFieldList = fieldList
},
getStatusList() {
initDictOptions('m_status').then(res => {
this.statusList = res.result
})
},
showModal(record) {
this.recordObj = record
getAction('/mbTemplate/mbwd').then(res => {
let list = res.result.map(item => {
// let name = item.documentTemplate.split('/')[1].split('.')[0]
let name = item.documentTemplate.split('.')[0]
return {
...item,
name: name
}
})
this.docList = this.statusList.map(item => {
return {
label: item.text,
children: list.filter(val => { return +val.status === +item.value })
}
})
this.docVisible = true
})
},
handlePrint() {
if(this.checkList.length === 0) {
this.$message.warning('请选择要下载的文档')
return
}
// if(this.checkList.length === 1) {
// this.handleDownloadXls(this.checkList[0])
// } else {
// // this.checkList.forEach(item => {
// // this.handleDownloadXls(item)
// // })
// }
let mbId = this.checkList.map(item => {return item.documentTemplate}).join(',')
this.handleDownloadZip(mbId)
},
handleDownloadZip(mbId) {
let fileName = this.recordObj.name + '文档'
downFile("/mbTemplate/export", {mbId: mbId, id: this.recordObj.id}).then(data => {
if (!data) {
this.$message.warning("下载文档失败")
return
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.zip')
} else {
let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + '.zip')
document.body.appendChild(link)
link.click()
document.body.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(url); //释放掉blob对象
}
this.docVisible = false
})
},
onChange(checkedValues) {
this.checkList = this.docList.map(item => {
return item.children.filter(val => { return checkedValues.includes(val.id) })
}).flat()
},
}
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.label {
padding-bottom: 10px;
font-size: 14px;
font-weight: bold;
color: #333;
}
.check-box + .check-box {
padding-top: 10px;
}
</style>
二 后端代码
MbTemplateController.java
package org.jeecg.modules.memplate.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.memplate.entity.MbExcel;
import org.jeecg.modules.memplate.entity.MbTemplate;
import org.jeecg.modules.memplate.service.IMbExcelService;
import org.jeecg.modules.memplate.service.IMbTemplateService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.memplate.vo.MbTemplateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
/**
* @Description: 个人贷款模板
* @Author: yxg
* @Date: 2022-10-09
* @Version: V1.0
*/
@Api(tags="个人贷款模板")
@RestController
@RequestMapping("/mbTemplate")
@Slf4j
public class MbTemplateController extends JeecgController<MbTemplate, IMbTemplateService> {
@Autowired
private IMbTemplateService mbTemplateService;
@Autowired
private IMbExcelService mbExcelService;
/**
* 下载文档
* @throws IOException
* @return
*/
@RequestMapping(value = "/export")
public void replace(HttpServletResponse request, MbTemplateVo mbTemplate) throws IOException {
mbTemplateService.inport(request, mbTemplate);
}
}
IMbTemplateService.java
package org.jeecg.modules.memplate.service;
import org.jeecg.modules.memplate.entity.MbTemplate;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.memplate.vo.MbTemplateVo;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description: 个人贷款模板
* @Author: yxg
* @Date: 2022-10-09
* @Version: V1.0
*/
public interface IMbTemplateService extends IService<MbTemplate> {
/**
* 下载文档打成压缩包
*
* @param request
* @param mbTemplate
* @return
* @throws IOException
*/
String inport(HttpServletResponse request, MbTemplateVo mbTemplate) throws IOException;
}
MbTemplateServiceImpl.java
package org.jeecg.modules.memplate.service.impl;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.memplate.entity.MbExcel;
import org.jeecg.modules.memplate.entity.MbTemplate;
import org.jeecg.modules.memplate.mapper.MbExcelMapper;
import org.jeecg.modules.memplate.mapper.MbTemplateMapper;
import org.jeecg.modules.memplate.service.IMbTemplateService;
import org.jeecg.modules.memplate.vo.MbTemplateVo;
import org.jeecg.modules.mortgage.entity.MbMortgage;
import org.jeecg.modules.mortgage.mapper.MbMortgageMapper;
import org.jeecg.modules.muarantee.entity.MbGuarantee;
import org.jeecg.modules.muarantee.mapper.MbGuaranteeMapper;
import org.jeecg.modules.utils.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description: 个人贷款模板
* @Author: yxg
* @Date: 2022-10-09
* @Version: V1.0
*/
@Service
public class MbTemplateServiceImpl extends ServiceImpl<MbTemplateMapper, MbTemplate> implements IMbTemplateService {
@Autowired
private MbTemplateMapper mbTemplateMapper;
@Autowired
private MbGuaranteeMapper mbGuaranteeMapper;
@Autowired
private MbMortgageMapper mbMortgageMapper;
@Autowired
private MbExcelMapper mbExcelMapper;
@Override
public String inport(HttpServletResponse request, MbTemplateVo mbTemplate, MbGuaranteeVO vo) throws IOException {
//先删除上次替换的文件夹内容
File file = new File("D://opt//yhzl//");
deleteFile(file);
//需要前端传来excel模板名称
String documentTemplate = "";
String[] res = mbTemplate.getMbId().split(",");
List<MbExcel> mbList = new ArrayList();
for (int i = 0; i < res.length; i++) {
documentTemplate = res[i];
MbExcel mbExcel=mbExcelMapper.selectmc(documentTemplate);
//路径后面的文件名(包括后缀)
File temp=new File(mbExcel.getDocumentPath().trim());
String filName=temp.getName();
String generateStyle="1";
LambdaQueryWrapper<MbExcel> lambdaQueryWrapper=new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(MbExcel::getDocumentTemplate,documentTemplate);
List<MbExcel>mbExcelList=mbExcelMapper.selectList(lambdaQueryWrapper);
if(mbExcelList.size()>0){
generateStyle=mbExcelList.get(0).getGenerateStyle();
}
//查找放在本地的excel模板
String path = "D://opt//upFiles//temp//" + filName;
//将替换后的excel放到新的文件夹为压缩做准备
String outPath = "D://opt//yhzl//" + filName;
//借款人id
String id = mbTemplate.getId();
//执行SQL语句,查询要替换的数据
MbTemplateVo mbTemplateVo = mbMortgageMapper.selectist(mbTemplate.getId());
//查询抵押物的list
String mbTemplateId = id;
List<MbMortgage> pageList = mbMortgageMapper.select(mbTemplateId);
mbTemplateVo.setMbMortgageList(pageList);
//借款人的资产
String zMbTemplateId = id;
List<MbAeests> mbAeestsList = mbAeestsMapper.select(zMbTemplateId);
mbTemplateVo.setMbAssetsList(mbAeestsList);
//担保人资产
String bMbTemplateId = id;
List<MbGuaranteeVO> bList = mbGuaranteeMapper.select(bMbTemplateId);
mbTemplateVo.setMbGuaranteeList(bList);
if(vo != null){
mbTemplateVo.getMbGuaranteeList().add(vo);
}
if (!mbTemplateVo.getMbGuaranteeList().isEmpty()) {
for (MbGuaranteeVO mbGuaranteeVO : mbTemplateVo.getMbGuaranteeList()) {
String bid = mbGuaranteeVO.getId();
List<MbAeests> list = mbAeestsMapper.sele(bid);
mbGuaranteeVO.setMbAssetsList(list);
}
}
Map<String, Object> params = new HashMap<String, Object>();
String sex = "";
String marital_status = "";
String sex_guarantor = "";
String SpouseAge = "";
String InterestSettlement = "";
String CreditRating = "";
String FiveCategories = "";
String DbCreditRating = "";
String db = "";
String zf = "";
String zh="";
String ynnll="";
String wnnl="";
//数据字典里面的值进行替换
if (mbTemplateVo.getGuaranteeMethod().equals("1")) {
db = "信用";
} else {
db = "其他";
}
if (mbTemplateVo.getPaymentMethod().equals("1")) {
zf = "自主支付";
} else {
zf = "其他";
}
if (mbTemplateVo.getDbCreditRating().equals("1")) {
DbCreditRating = "A级";
} else if (mbTemplateVo.getDbCreditRating().equals("2")) {
DbCreditRating = "B级";
} else if (mbTemplateVo.getDbCreditRating().equals("3")) {
DbCreditRating = "C级";
} else if (mbTemplateVo.getDbCreditRating().equals("4")) {
DbCreditRating = "D级";
} else {
DbCreditRating = "E级";
}
if (mbTemplateVo.getFiveCategories().equals("1")) {
FiveCategories = "正常";
} else if (mbTemplateVo.getFiveCategories().equals("2")) {
FiveCategories = "关注";
} else if (mbTemplateVo.getFiveCategories().equals("3")) {
FiveCategories = "次级";
} else if (mbTemplateVo.getFiveCategories().equals("4")) {
FiveCategories = "可疑";
} else {
FiveCategories = "损失";
}
// if (mbTemplateVo.getCreditRating().equals("1")) {
// CreditRating = "A级";
// } else if(mbTemplateVo.getCreditRating().equals("2")){
// CreditRating = "B级";
// }else if(mbTemplateVo.getCreditRating().equals("3")){
// CreditRating = "C级";
// }else if(mbTemplateVo.getCreditRating().equals("4")){
// CreditRating = "D级";
// }else {
// CreditRating = "E级";
// }
if (mbTemplateVo.getInterestSettlement().equals("1")) {
InterestSettlement = "按月还款";
} else {
InterestSettlement = "按季度还款";
}
if (mbTemplateVo.getSpouseAge() == null) {
SpouseAge = "";
} else {
if (mbTemplateVo.getSpouseAge().equals("1")) {
SpouseAge = "男";
} else {
SpouseAge = "女";
}
}
if (mbTemplateVo.getSex().equals("1")) {
sex = "男";
} else {
sex = "女";
}
if (mbTemplateVo.getMaritalStatus().equals("1")) {
marital_status = "已婚";
} else if (mbTemplateVo.getMaritalStatus().equals("2")) {
marital_status = "未婚";
} else {
marital_status = "离婚";
}
if (mbTemplateVo.getSexGuarantor() == null) {
sex_guarantor = "";
} else {
if (mbTemplateVo.getSexGuarantor().equals("1")) {
sex_guarantor = "男";
} else {
sex_guarantor = "女";
}
}
//借款人资产
String jkrzcmc = "";
String assName = "";
String jkrzcjz = "";
String jkrzcms = "";
String jkrzcqk = "";
String jkrzcqkName = "";
int j = 1;
for (MbAeests mbAeests : mbTemplateVo.getMbAssetsList()) {
jkrzcmc = "jkrzcmc" + j;
jkrzcjz = "jkrzcjz" + j;
jkrzcms = "jkrzcms" + j;
jkrzcqk = "jkrzcqk" + j;
if (mbAeests.getAssetName().equals("1")) {
assName = "A固定";
} else {
assName = "B流动";
}
if (mbAeests.getWnershipCertificate().equals("1")) {
jkrzcqkName = "A房产证";
} else if (mbAeests.getWnershipCertificate().equals("2")) {
jkrzcqkName = "B购房/借款合同,发票";
} else if (mbAeests.getWnershipCertificate().equals("3")) {
jkrzcqkName = "C村证明";
} else if (mbAeests.getWnershipCertificate().equals("4")) {
jkrzcqkName = "D土地使用权证";
} else if (mbAeests.getWnershipCertificate().equals("5")) {
jkrzcqkName = "E有价证";
} else if (mbAeests.getWnershipCertificate().equals("6")) {
jkrzcqkName = "F车辆登记证/行驶证";
} else if (mbAeests.getWnershipCertificate().equals("7")) {
jkrzcqkName = "H公司报表";
} else {
jkrzcqkName = "I其它";
}
params.put(jkrzcmc, assName);
params.put(jkrzcjz, mbAeests.getAssetValue());
params.put(jkrzcms, mbAeests.getAssetDescription());
params.put(jkrzcqk, jkrzcqkName);
j++;
}
//担保人信息
String dbrfz = "";
String dbrm = " ";
String dbrxm = "";
List<String> dbrxms = new ArrayList<>();
String dbrsfz = "";
List<String> dbrsfzs = new ArrayList<>();
String dbrdz = "";
String dbfs = "";
String dbfsName = "";
String dbrxb = "";
String dbrxbSex = "";
String dbrdh = "";
int k = 1;
// MbGuaranteeVO mbGuaranteeVO = vo;
if (mbTemplateVo.getMbGuaranteeList() != null) {
for (MbGuaranteeVO mbGuaranteeVO : mbTemplateVo.getMbGuaranteeList()) {
dbrm = "dbrm";
dbrfz = "dbrfz";
dbrxm = "dbrxm" + k;
dbrsfz = "dbrsfz" + k;
dbrdz = "dbrdz" + k;
dbfs = "dbfs" + k;
dbrxb = "dbrxb" + k;
dbrdh = "dbrdh" + k;
if (mbGuaranteeVO.getSexGuarantor().equals("1")) {
dbrxbSex = "男";
} else {
dbrxbSex = "女";
}
if (mbGuaranteeVO.getGuaranteeMethod().equals("1000")) {
dbfsName = "信用担保";
} else if (mbGuaranteeVO.getGuaranteeMethod().equals("2000")) {
dbfsName = "保证担保";
} else if (mbGuaranteeVO.getGuaranteeMethod().equals("3000")) {
dbfsName = "质押";
} else {
dbfsName = "抵押担保";
}
dbrxms.add(mbGuaranteeVO.getNameOfGuarantor());
dbrsfzs.add(mbGuaranteeVO.getIdCardGuarantor());
params.put(dbrfz, mbGuaranteeVO.getIdCardGuarantor());
params.put(dbrm, mbGuaranteeVO.getNameOfGuarantor());
params.put(dbrdh, mbGuaranteeVO.getPhoneGuarantor());
params.put(dbrxb, dbrxbSex);
params.put(dbfs, dbfsName);
params.put(dbrxm, mbGuaranteeVO.getNameOfGuarantor());
params.put(dbrsfz, mbGuaranteeVO.getIdCardGuarantor());
params.put(dbrdz, mbGuaranteeVO.getAdderGuarantor());
//担保人资产
int m = 1;
//第一个担保人资产
String dbrxmdbrzcmc = "";
String dbrxmdbrzcmcName = "";
String dbrxmdbrzcms = "";
String dbrxmdbrzcjz = "";
String dbrxmdbrzcqk = "";
String dbrxmdbrzcqkName = "";
for (MbAeests mbAeests : mbGuaranteeVO.getMbAssetsList()) {
dbrxmdbrzcmc = "dbrxm" + k + "dbrzcmc" + m;
dbrxmdbrzcms = "dbrxm" + k + "dbrzcms" + m;
dbrxmdbrzcjz = "dbrxm" + k + "dbrzcjz" + m;
dbrxmdbrzcqk = "dbrxm" + k + "dbrzcqk" + m;
if (mbAeests.getAssetName().equals("1")) {
dbrxmdbrzcmcName = "A固定";
} else {
dbrxmdbrzcmcName = "B流动";
}
if (mbAeests.getWnershipCertificate().equals("1")) {
dbrxmdbrzcqkName = "A房产证";
} else if (mbAeests.getWnershipCertificate().equals("2")) {
dbrxmdbrzcqkName = "B购房/借款合同,发票";
} else if (mbAeests.getWnershipCertificate().equals("3")) {
dbrxmdbrzcqkName = "C村证明";
} else if (mbAeests.getWnershipCertificate().equals("4")) {
dbrxmdbrzcqkName = "D土地使用权证";
} else if (mbAeests.getWnershipCertificate().equals("5")) {
dbrxmdbrzcqkName = "E有价证";
} else if (mbAeests.getWnershipCertificate().equals("6")) {
dbrxmdbrzcqkName = "F车辆登记证/行驶证";
} else if (mbAeests.getWnershipCertificate().equals("7")) {
dbrxmdbrzcqkName = "H公司报表";
} else {
dbrxmdbrzcqkName = "I其它";
}
params.put(dbrxmdbrzcmc, dbrxmdbrzcmcName);
params.put(dbrxmdbrzcjz, mbAeests.getAssetValue());
params.put(dbrxmdbrzcms, mbAeests.getAssetDescription());
params.put(dbrxmdbrzcqk, dbrxmdbrzcqkName);
m++;
}
k++;
}
}
//
params.put("dbrxms", String.join(",", dbrxms));
params.put("dbrsfzs", String.join(",", dbrsfzs));
//抵押人信息
String dyrxm = "";
String dyrsfz = "";
String dyrdh = "";
String dyrdz = "";
String dywpmc = "";
String dyName = "";
String dywpwz = "";
String bdzcbh = "";
String dyl = "";
String pgfs = "";
String yjkrgx = "";
String gyrxm = "";
String zjhm = "";
String tdsymj = "";
String fcmj = "";
String dywpjz = "";
String pgjz = "";
String mpfygjz = "";
String kdzg = "";
String bzhxq = "";
String pggs = "";
String zcqk = "";
String fzqk = "";
String dbqk = "";
int t = 1;
for (MbMortgage mbMortgage : mbTemplateVo.getMbMortgageList()) {
dyrxm = "dyrxm" + t;
zcqk = "zcqk" + t;
fzqk = "fzqk" + t;
dbqk = "dbqk" + t;
dyrsfz = "dyrsfz" + t;
dyrdh = "dyrdh" + t;
dyrdz = "dyrdz" + t;
dywpmc = "dyepmc" + t;
dywpwz = "dywpwz" + t;
bdzcbh = "bdzcbh" + t;
dyl = "dyl" + t;
pgfs = "pgfs" + t;
yjkrgx = "yjkrgx" + t;
gyrxm = "gyrxm" + t;
zjhm = "zjhm" + t;
tdsymj = "tdsymj" + t;
fcmj = "fcmj" + t;
dywpjz = "dywpjz" + t;
pgjz = "pgjz" + t;
mpfygjz = "mpfygjz" + t;
kdzg = "kdzg" + t;
bzhxq = "bzhxq" + t;
pggs = "pggs" + t;
if (mbMortgage.getNameOfCollateral().equals("1")) {
dyName = "房子";
} else {
dyName = "车子";
}
params.put(dbqk, mbMortgage.getGuarantee());
params.put(fzqk, mbMortgage.getLiabilities());
params.put(zcqk, mbMortgage.getAssets());
params.put(pggs, mbMortgage.getCompanyNumber());
params.put(bzhxq, mbMortgage.getAppraisalName());
params.put(kdzg, mbMortgage.getAmountPrice());
params.put(mpfygjz, mbMortgage.getAppraisalPrice());
params.put(pgjz, mbMortgage.getAppraisalValue());
params.put(dywpjz, mbMortgage.getMortgageValue());
params.put(fcmj, mbMortgage.getHomeNumber());
params.put(tdsymj, mbMortgage.getAreaNumber());
params.put(zjhm, mbMortgage.getDentificationNumber());
params.put(gyrxm, mbMortgage.getBorrowerName());
params.put(yjkrgx, mbMortgage.getBorrowerMethod());
params.put(pgfs, mbMortgage.getEvaluationMethod());
params.put(dyl, mbMortgage.getPledgeRate());
params.put(bdzcbh, mbMortgage.getErtificateNumber());
params.put(dywpwz, mbMortgage.getMortgageAdder());
params.put(dywpmc, dyName);
params.put(dyrdz, mbMortgage.getAdderFalse());
params.put(dyrdh, mbMortgage.getMortgagePhone());
params.put(dyrxm, mbMortgage.getMortgageOfName());
params.put(dyrsfz, mbMortgage.getMortgageIdCard());
t++;
}
//替换的值先放进一个map里面,然后再遍历excel模板进行替换,比如说把{xm}替换成张三
params.put("xm", mbTemplateVo.getName());
params.put("nl", mbTemplateVo.getAge());
params.put("xb", sex);
params.put("dz", mbTemplateVo.getAdder());
params.put("lxdh", mbTemplateVo.getPhone());
params.put("khjl", mbTemplateVo.getAccountManager());
params.put("jkje", mbTemplateVo.getLoanAmount());
params.put("jkqx", mbTemplateVo.getLoanTerm());
params.put("hyzk", marital_status);
params.put("wd", mbTemplateVo.getNetwork());
params.put("sfz", mbTemplateVo.getIdCard());
params.put("xjdz", mbTemplateVo.getCurrentResidence());
params.put("jyxm", mbTemplateVo.getBusinessMajor());
params.put("jydz", mbTemplateVo.getBusinessAddress());
params.put("jynx", mbTemplateVo.getOperatingLife());
params.put("jtnsr", mbTemplateVo.getHouseholdIncome());
params.put("jtnzc", mbTemplateVo.getHouseholdExpenditure());
params.put("jtrk", mbTemplateVo.getHouneNome());
params.put("jkxz", mbTemplateVo.getLoanNature());
params.put("jkyt", mbTemplateVo.getUsageOfLoan());
params.put("nll", mbTemplateVo.getAnnualInterest());
params.put("hkzjly", mbTemplateVo.getRepaymentFunds());
params.put("pexm", mbTemplateVo.getSpouseName());
params.put("pexb", SpouseAge);
params.put("pesfz", mbTemplateVo.getSpouseIdCard());
params.put("rjckje", mbTemplateVo.getOmogeneousAmount());
params.put("zzc", mbTemplateVo.getTotalAssets());
params.put("tqqtyhje", mbTemplateVo.getBalanceAmount());
params.put("zfz", mbTemplateVo.getTotalLiabilities());
params.put("jzc", mbTemplateVo.getNetAssets());
params.put("rgje", mbTemplateVo.getAmountOfShares());
params.put("thdky", mbTemplateVo.getOtherBanks());
params.put("sm", mbTemplateVo.getTexts());
params.put("dwdb", mbTemplateVo.getGuaranteedBanks());
params.put("jxhk", InterestSettlement);
params.put("pgfs", mbTemplateVo.getEvaluationMethod());
params.put("jkrxy", mbTemplateVo.getCreditRating());
params.put("dbrxy", DbCreditRating);
params.put("wl", FiveCategories);
params.put("zhje", mbTemplateVo.getCreditBanks());
params.put("xq", mbTemplateVo.getAppraisalName());
params.put("gj", mbTemplateVo.getAppraisalPrice());
params.put("mj", mbTemplateVo.getHomeNumber());
params.put("dyl", mbTemplateVo.getPledgeRate());
params.put("zg", mbTemplateVo.getAmountPrice());
params.put("db", db);
params.put("zf", zf);
params.put("yt", mbTemplateVo.getUsageOfLoan());
params.put("jkrgx", mbTemplateVo.getBorrowerMethod());
params.put("gyrxm", mbTemplateVo.getBorrowerName());
params.put("zjhm", mbTemplateVo.getDentificationNumber());
params.put("tdsyq", mbTemplateVo.getAreaNumber());
params.put("fcmj", mbTemplateVo.getHomeNumber());
params.put("pggs", mbTemplateVo.getCompanyNumber());
params.put("qzh", mbTemplateVo.getErtificateNumber());
params.put("jz", mbTemplateVo.getAppraisalValue());
params.put("mtfm", mbTemplateVo.getAppraisalPrice());
params.put("fzdyl", mbTemplateVo.getPledgeRate());
params.put("zh", mbTemplateVo.getTransactionAccount());
params.put("khh", mbTemplateVo.getBankOfDeposit());
params.put("ynnll", mbTemplateVo.getOneInterest());
params.put("wnnl", mbTemplateVo.getLifeInterest());
//一张一张导出
//导出前先进行文件夹文件内容删除
//获取前端传来的文件后缀判断是xlsx还是docx的
String suffix = filName.substring(filName.lastIndexOf("."), filName.length());
if (suffix.equals(".xlsx") || suffix.equals(".xls")) {
//后缀为xlsx或者xls
if(generateStyle.equals("1")){
replaceExcel(request, path, outPath, params);
}else{
replaceExcel(request, path, outPath, params);
}
} else {
//后缀为docx或者doc
replaceDocx(path, outPath, params, suffix);
}
}
//打成zip包
String srcFileDir = "D://opt//yhzl//";
//下载到本地
// String destFile = "D:\opt\" + mbTemplate.getId() + ".zip";
// FileOutputStream fos = new FileOutputStream(destFile);
// ZipUtil.toZip(srcFileDir, fos, true);
//下载到浏览器进行展示
ServletOutputStream out = request.getOutputStream();
ZipUtil.toZip(srcFileDir, out, true);
return documentTemplate;
}
/**
* 删除文件夹下内容
* @param file
*/
public void deleteFile(File file) {
//判断文件不为null或文件目录存在
if (file == null || !file.exists()) {
flag = 0;
System.out.println("文件删除失败,请检查文件路径是否正确");
return;
}
//取得这个目录下的所有子文件对象
File[] files = file.listFiles();
//遍历该目录下的文件对象
for (File f : files) {
//打印文件名
String name = file.getName();
System.out.println(name);
//判断子目录是否存在子目录,如果是文件则删除
if (f.isDirectory()) {
deleteFile(f);
} else {
f.delete();
}
}
//删除空文件夹 for循环已经把上一层节点的目录清空。
// file.delete();
}
//doc的文档模板
public void replaceDocx(String inPath, String outPath, Map<String, Object> params, String suffix) throws IOException, InvalidFormatException {
Document doc1 = new Document();
doc1.loadFromFile(inPath);
if(params.containsKey("jkrzcmc1")){
}else {
params.put("jkrzcmc1", " ");
params.put("jkrzcjz1"," ");
params.put("jkrzcms1"," ");
params.put("jkrzcqk1", " ");
}
if(params.containsKey("dyrxm1")){
}else {
params.put("dbqk1", " ");
params.put("fzqk1", " ");
params.put("zcqk1", " ");
params.put("pggs1", " ");
params.put("bzhxq1", " ");
params.put("kdzg1", " ");
params.put("mpfygjz1"," ");
params.put("pgjz1", " ");
params.put("dywpjz1"," ");
params.put("fcmj1", " ");
params.put("tdsymj1", " ");
params.put("zjhm1", " ");
params.put("gyrxm1", " ");
params.put("yjkrgx1", " ");
params.put("pgfs1"," ");
params.put("dyl1", " ");
params.put("bdzcbh1"," ");
params.put("dywpwz1", " ");
params.put("dyepmc1"," ");
params.put("dyrdz1"," ");
params.put("dyrdh1", " ");
params.put("dyrxm1"," ");
params.put("dyrsfz1"," ");
}
if(params.containsKey("dbrxm1") ){
}else {
params.put("dbrxm1", " ");
params.put("dbrsfz1", " ");
params.put("dbrdz1", " ");
params.put("dbrdh1", " ");
params.put("dbrxb1","");
params.put("dbrfs1"," ");
params.put("dbrxm1dbrzcmc1"," ");
params.put("dbrxm1dbrzcjz1", " ");
params.put("dbrxm1dbrzcms1"," ");
params.put("dbrxm1dbrzcqk1", " ");
}
if(params.containsKey("dyrxm2")){
}else {
params.put("dbqk2", " ");
params.put("fzqk2", " ");
params.put("zcqk2", " ");
params.put("pggs2", " ");
params.put("bzhxq2", " ");
params.put("kdzg2", " ");
params.put("mpfygjz2"," ");
params.put("pgjz2", " ");
params.put("dywpjz2"," ");
params.put("fcmj2", " ");
params.put("tdsymj2", " ");
params.put("zjhm2", " ");
params.put("gyrxm2", " ");
params.put("yjkrgx2", " ");
params.put("pgfs2"," ");
params.put("dyl2", " ");
params.put("bdzcbh2"," ");
params.put("dywpwz2", " ");
params.put("dyepmc2"," ");
params.put("dyrdz2"," ");
params.put("dyrdh2", " ");
params.put("dyrxm2"," ");
params.put("dyrsfz2"," ");
}
if(params.containsKey("dbrxm2") ){
}else {
params.put("dbrxm2", " ");
params.put("dbrsfz2", " ");
params.put("dbrdz2", " ");
params.put("dbrdh2", " ");
params.put("dbrxb2","");
params.put("dbrfs2"," ");
params.put("dbrxm2dbrzcmc2"," ");
params.put("dbrxm2dbrzcjz2", " ");
params.put("dbrxm2dbrzcms2"," ");
params.put("dbrxm2dbrzcqk2", " ");
}
if(params.containsKey("dbrxm3")){
}else {
params.put("dbrxm3", " ");
params.put("dbrsfz3", " ");
params.put("dbrdz3", " ");
params.put("dbrdh3", " ");
params.put("dbrxb3","");
params.put("dbrfs3"," ");
params.put("dbrxm3dbrzcmc3"," ");
params.put("dbrxm3dbrzcjz3", " ");
params.put("dbrxm3dbrzcms3"," ");
params.put("dbrxm3dbrzcqk3", " ");
}
if (params.containsKey("dyrxm3")) {
}else {
params.put("dbqk3", " ");
params.put("fzqk3", " ");
params.put("zcqk3", " ");
params.put("pggs3", " ");
params.put("bzhxq3", " ");
params.put("kdzg3", " ");
params.put("mpfygjz3"," ");
params.put("pgjz3", " ");
params.put("dywpjz3"," ");
params.put("fcmj3", " ");
params.put("tdsymj3", " ");
params.put("zjhm3", " ");
params.put("gyrxm3", " ");
params.put("yjkrgx3", " ");
params.put("pgfs3"," ");
params.put("dyl3", " ");
params.put("bdzcbh3"," ");
params.put("dywpwz3", " ");
params.put("dyepmc3"," ");
params.put("dyrdz3"," ");
params.put("dyrdh3", " ");
params.put("dyrxm3"," ");
params.put("dyrsfz3"," ");
}
for (String key : params.keySet()) {
String val = params.get(key) == null ? "" : params.get(key).toString();
key = "{" + key + "}";
doc1.replace(key, val, false, true);
}
//保存文档1
if(suffix.equals(".docx")){
doc1.saveToFile(outPath, FileFormat.Docx_2013);
}else {
doc1.saveToFile(outPath, FileFormat.Doc);
}
doc1.dispose();
}
//xlsx的文档模板
public void replaceExcel(HttpServletResponse request, String inPath, String outPath, Map params) throws IOException, InvalidFormatException {
InputStream is = new FileInputStream(inPath);
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);//获取Excel的工作表sheet,下标从0开始。
//int trLength = sheet.getLastRowNum();//获取Excel的行数
int trLength = sheet.getPhysicalNumberOfRows();//获得总行数
for (int i = 0; i < trLength; i++) {
Row row = sheet.getRow(i);//获取Excel的行,下标从0开始
if (row == null) {//若行为空,则遍历下一行
continue;
}
int minColIx = row.getFirstCellNum();
int maxColIx = row.getLastCellNum();
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
Cell cell = row.getCell(colIx);//获取指定单元格,单元格从左到右下标从0开始
if(cell==null){
continue;
}
//String runText = cell.getStringCellValue();
String runText = "";
if (cell.getCellType().equals(CellType.STRING)) {
runText = cell.getStringCellValue();
}
if (cell.getCellType().equals(CellType.NUMERIC)) {
runText = String.valueOf(cell.getNumericCellValue());
}
//NUMERIC
if (runText.equals("")) {
continue;
}
Matcher matcher = this.matcher(runText);
if (matcher.find()) {
while ((matcher = this.matcher(runText)).find()) {
String val=String.valueOf(params.get(matcher.group(1)));
//判断下载文档里面有没有null 有就用空替换
if("null".equals(val)|| StringUtils.isEmpty(val)){
val = "";
}
runText = matcher.replaceFirst(val);
}
String cellVal=cell.getStringCellValue();
if(cellVal.contains("jkrzcmc")&&runText.equals("null")||
cellVal.contains("dbrzcmc")&&runText.equals("null")){
int index=getMergedRegion(sheet,row);
//解除合并单元格
sheet.removeMergedRegion(index);
//删除行
sheet.shiftRows(row.getRowNum()+1, sheet.getLastRowNum(),-1);
i--;
break;
}else{
//如果替换的字段没值那么excel会显示null 这里判断一下,如果为null就用" "替换
if(runText.equals("null")){
runText="";
}
cell.setCellValue(runText);
}
}
}
}
//下载到本地磁盘里面
OutputStream out = new FileOutputStream(new File(outPath));
//单独下载到浏览器进行excel显示
// ServletOutputStream out = request.getOutputStream();
wb.write(out);
is.close();
out.close();
}
/**
* 正则匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\{(.+?)\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
}
提供了zip的压缩和解压的api
package org.jeecg.modules.utils;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.*;
/**
* 提供了zip的压缩和解压方法
*/
public class ZipUtil {
/**
* 文件夹压缩成ZIP
*
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 文件列表压缩成ZIP
*
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[1024];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[1024];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
* 解压缩zip包
*
* @param zipFilePath zip文件的全路径
* @param destPath 解压后的文件保存的路径
* @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
public static void unzip(String zipFilePath, String destPath, boolean includeZipFileName) throws Exception {
if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(destPath)) {
throw new Exception();
}
File zipFile = new File(zipFilePath);
//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if (includeZipFileName) {
String fileName = zipFile.getName();
if (null != fileName && !"".equals(fileName)) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
destPath = destPath + File.separator + fileName + File.separator;
}
File destPathFile = new File(destPath);
// 创建文件夹
if (!destPathFile.exists() || !destPathFile.isDirectory()) {
destPathFile.mkdirs();
}
//开始解压
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
//循环对压缩包里的每一个文件进行解压
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName().replace("/", File.separator);
String destFilePath = destPath + File.separator + entryName;
String outPath = destFilePath.substring(0, destFilePath.lastIndexOf(File.separator));
File pathFile = new File(outPath);
// 创建文件夹
if (!pathFile.exists() || !pathFile.isDirectory()) {
pathFile.mkdirs();
}
File destFile = new File(destFilePath);
// 判断是否为文件夹
if (destFile.isDirectory()) {
continue;
}
//删除已存在的文件
/*if (destFile.exists()) {
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
*//*SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(destFilePath);*//*
//删除已存在的目标文件
destFile.delete();
}*/
//写入文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
InputStream inputStream = zip.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
bis.close();
inputStream.close();
}
zip.close();
}
/**
* 测试方法
* 注意:操作时会覆盖重名文件
*
* @param args
*/
public static void main(String[] args) {
try {
// 1、压缩文件夹
zipDirTest();
// // 2、压缩文件列表
// zipFileListTest();
// // 3、解压测试
// unzipTest();
} catch (Exception e) {
e.printStackTrace();
}
}
// private static void unzipTest() throws Exception {
// String zipFilePath = "F:\testzip.zip";
// String unzipFilePath = "F:\unzip";
// unzip(zipFilePath, unzipFilePath, false);
// }
//
// private static void zipFileListTest() throws FileNotFoundException {
// String srcFile = "F:\testzip\1.txt";
// String destFile = "F:\testzip\1.zip";
// FileOutputStream fos = new FileOutputStream(destFile);
// toZip(Arrays.asList(new File(srcFile)), fos);
// }
private static void zipDirTest() throws FileNotFoundException {
String srcFileDir = "D:\opt\upFiles\temp";
String destFile = "D:\opt\testzip.zip";
FileOutputStream fos = new FileOutputStream(destFile);
toZip(srcFileDir, fos, true);
}
}
提供删除文件夹下面内容的方法
//先删除上次替换的文件夹内容 File file = new File("D:\opt\银行资料\"); deleteFile(file); /** * 删除文件夹下内容 * @param file */ public void deleteFile(File file) { //判断文件不为null或文件目录存在 if (file == null || !file.exists()) { flag = 0; System.out.println("文件删除失败,请检查文件路径是否正确"); return; } //取得这个目录下的所有子文件对象 File[] files = file.listFiles(); //遍历该目录下的文件对象 for (File f : files) { //打印文件名 String name = file.getName(); System.out.println(name); //判断子目录是否存在子目录,如果是文件则删除 if (f.isDirectory()) { deleteFile(f); } else { f.delete(); } } //删除空文件夹 for循环已经把上一层节点的目录清空。 // file.delete(); } /** * 获取所在行的合并单元格cell的位置 * * @param sheet * @param row * @return */ public int getMergedRegion(Sheet sheet, Row row) { int sheetMergeCount = sheet.getNumMergedRegions();//获取所有的单元格 int index = 0;//用于保存要移除的那个单元格序号 for (int j = 0; j < sheetMergeCount; j++) { CellRangeAddress ca = sheet.getMergedRegion(j); //获取第i个单元格 int firstColumn = ca.getFirstColumn(); int lastColumn = ca.getLastColumn(); int firstRow = ca.getFirstRow(); int lastRow = ca.getLastRow(); int minColIx = row.getFirstCellNum(); int maxColIx = row.getLastCellNum(); for (int colIx = minColIx; colIx < maxColIx; colIx++) { if (row.getRowNum() >= firstRow && row.getRowNum() <= lastRow) { if (colIx >= firstColumn && colIx <= lastColumn) { index = j; } } } } return index; }
最后
以上就是飞快小蘑菇为你收集整理的Java根据excel/word模板进行值替换并且打成压缩包一 前端代码(MbTemplateList.vue)二 后端代码MbTemplateController.javaIMbTemplateService.javaMbTemplateServiceImpl.java提供了zip的压缩和解压的api提供删除文件夹下面内容的方法的全部内容,希望文章能够帮你解决Java根据excel/word模板进行值替换并且打成压缩包一 前端代码(MbTemplateList.vue)二 后端代码MbTemplateController.javaIMbTemplateService.javaMbTemplateServiceImpl.java提供了zip的压缩和解压的api提供删除文件夹下面内容的方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复