文章目录
- xlsx文件转化成json
- 将前端传递的 json数据 用类的方式接收
- 获取传入JSON,转化为想要的数据格式
- JOSN转实体类、实体类转JSON
- 截取浏览器的 token
- 根据后端传递的数据展示不同的信息 方式一
- 根据后端传递的数据展示不同的信息 方式二
- 判断当前的时间在某一个时段内
- vue中引入另一个页面
- 获取JSON数据 一级 二级 数据
- 数据库转化时间格式
- 路由跳转
- 查询 当天/一周/一个月/三个月/半年/一年的 订单
- vue路由跳转
- 查询数据 page
- BigDecimal 数据处理
- java中比较两个日期的大小的所有方式
- 传递参数的几种方式
- logback.xml 生成日志 位置resource 下
- Vue封装组件
- 实体类中可拓展的Dao类想实现MyBatisPlus
- 导出excel功能
- StringUtils.hasText(字符串)的作用
- String截取文件路径
- 时间选择器限制选择日期
- Vue 文件下载
- Vue 上传组件
xlsx文件转化成json
package io.renren;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
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;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Serialnumber {
/**
* 获取如今时间
* @return返回字符串格式yyyyMMddHHmmss
*/
public static String getStringDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(date);
return dateString;
}
/**
* 由年月日时分秒+3位随机数
* 生成流水号
* @return
*/
public static String Getnum(Date date){
System.out.println("date = " + date);
String t = getStringDate(date);
System.out.println("t = " + t);
int x=(int)(Math.random()*900000)+100000;
String serial = t + x;
return serial;
}
//主方法测试
public static void main(String[] args) {
ArrayList<Map<String, String>> mapList = new ArrayList<>();
File file = new File("D:\\工作簿1000.xlsx");
// File file = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹 (3)\\工作簿1000.xlsx");
// System.out.println(file.getPath());
//获取文件的后缀名 \\ .是特殊字符
String[] split = file.getName().split("\\.");
// System.out.println(split[1]);
Workbook wb = null;
//根据文件后缀(xls/xlsx)进行判断
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
if ("xls".equals(split[1])) {
// //获取文件流对象
try {
wb = new HSSFWorkbook(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}else if ("xlsx".equals(split[1])){
try {
wb = new XSSFWorkbook(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//开始解析
Sheet sheet = wb.getSheetAt(0);
//第一行是列名,所以从第二行开始遍历
int firstRowNum = sheet.getFirstRowNum() + 1;
int lastRowNum = sheet.getLastRowNum();
//遍历行
for (int rIndex = firstRowNum; rIndex <= lastRowNum; rIndex++) {
Map map =new HashMap();
//获取当前行的内容
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getLastCellNum();
for (int cIndex = firstCellNum; cIndex < lastCellNum; cIndex++) {
row.getCell(cIndex).setCellType(CellType.STRING);
//获取单元格的值
String value = row.getCell(cIndex).getStringCellValue();
//获取此单元格对应第一行的值
String key = sheet.getRow(0).getCell(cIndex).getStringCellValue();
//第一行中的作为键,第n行的作为值
map.put(key, value);
}
}
// System.out.println("map = " + map);
mapList.add(map);
// ArrayList<Map<String, String>> parentList = new ArrayList<>();
// System.out.println("lastList = " + lastList);
}
JSONArray parentList = new JSONArray();
JSONArray lastList = new JSONArray();
Integer index = 14;
for (Map<String, String> stringStringMap : mapList) {
if(stringStringMap.get("类别码")==null){
JSONObject category = new JSONObject();
category.put("id",stringStringMap.get("序号"));
category.put("code",stringStringMap.get("序号"));
category.put("name",stringStringMap.get("分类"));
// ProTaskOrSucess proTaskOrSucess = new ProTaskOrSucess();
// proTaskOrSucess.setName(stringStringMap.get("分类"));
// proTaskOrSucess.setCode(stringStringMap.get("序号"));
// int count= handleDataService.saveByASS(proTaskOrSucess);
// System.out.println("count = " + count);
// System.out.println("77777");
System.out.println("stringStringMap = " + stringStringMap);
JSONArray children = new JSONArray();
for (Map<String, String> subCategory : mapList) {
if (subCategory.get("parent_id") == stringStringMap.get("序号")) {
JSONObject child = new JSONObject();
index++;
child.put("id", index);
child.put("parent_id", subCategory.get("parent_id"));
child.put("code", subCategory.get("类别码"));
child.put("name", subCategory.get("类别名称"));
children.add(child);
}
}
category.put("children", children);
parentList.add(category);
}
}
System.out.println("parentList = " + parentList);
// for (Object chiled : parentList) {
// JSONObject chiledObject = JSONObject.parseObject(JSONObject.toJSONString(chiled));
// JSONArray chiledList = new JSONArray();
// for (Map<String, String> stringStringMap : mapList) {
// System.out.println("stringStringMap.get(\"类别码\") = " + stringStringMap.get("类别码"));
// if(stringStringMap.get("类别码")!=null){
// System.out.println("88888888");
// if(chiledObject.get("parent_id").equals(stringStringMap.get("序号"))){
// System.out.println("33333");
// JSONObject chiledO = new JSONObject();
// chiledO.put("parent_id",stringStringMap.get("parent_id"));
// chiledO.put("类别名称",stringStringMap.get("类别名称"));
// chiledO.put("类别码",stringStringMap.get("类别码"));
// chiledList.add(chiledO);
// }
// }
// }
// chiledObject.put("children",chiledList);
// lastList.add(chiledObject);
// }
}
}
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
将前端传递的 json数据 用类的方式接收
UserVoucherVO userVoucherVO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), UserVoucherVO.class);
public class UserVoucherVO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer type;
private Integer userId;
private Integer pageNo;
private Integer pageSize;
private String name;
private String cover;
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
private String endTime;
private Integer price;
private Integer voucherId;
private Integer sailPrice;
private Integer trackId;
}
获取传入JSON,转化为想要的数据格式
public R wxPay(@RequestBody String json, HttpServletRequest request) {}
JSONObject jsonObject = JSON.parseObject(json);
String orderId = jsonObject.getString("orderId");
JOSN转实体类、实体类转JSON
//转换为json
String json = JsonUtil.objectToJson(person);
// {"name":"张三","age":10,"description":"张三,十岁了"}
System.out.println(json);
//json转换为对象
Person person1 = JsonUtil.jsonToObject(json, Person.class);
截取浏览器的 token
document.cookie.split("token")[1].split("=")[1]
<el-form-item label="图片" prop="cover">
<el-upload
class="upload-demo"
action="" # 请求拦截地址
:on-preview="handlePreview"
:on-remove="handleRemove"
:headers="token"
:limit="maxNum"
:file-list="fileList"
v-model="dataForm.cover"
list-type="picture"
:on-success='postOk'
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb,且只能上传一张图片
</div>
</el-upload>
</el-form-item>
data() {
return {
token: {
token: "",
},
};
},
created() {
// console.log(document.cookie.split("token")[1]);
// console.log(document.cookie.split("token")[1].split("=")[1])
this.token.token = document.cookie.split("token")[1].split("=")[1]
console.log(this.token.token);
},
根据后端传递的数据展示不同的信息 方式一
<el-table-column
prop="isSendByPromoed"
header-align="center"
align="center"
:formatter="isSendByPromoedShow"
label="被推广人的是否可以领取"
>
</el-table-column>
<el-table-column
prop="isSendByPromo"
header-align="center"
align="center"
:formatter="isSendByPromoShow"
label="推广人的是否可以领取"
>
</el-table-column>
methods: {
// 推广人和 被推广人 根据传入过来的数字展示不同的信息
isSendByPromoedShow(row) {
if (row.isSendByPromoed === 1) {
return "可以";
} else if (row.isSendByPromoed === 0) {
return "不可以";
}
},
isSendByPromoShow(row) {
if (row.isSendByPromo === 1) {
return "可以";
} else if (row.isSendByPromo === 0) {
return "不可以";
}
},
}
根据后端传递的数据展示不同的信息 方式二
根据传入的数值,来展示不同的值,可以更换字体颜色
<template slot-scope="scope">
<el-tag v-if="scope.row.goodsShelves === 0" size="medium" type="success" style="color: #96db6c">上架</el-tag>
<el-tag v-if="scope.row.goodsShelves === 1" size="medium" type="danger" >下架</el-tag>
</template>
判断当前日期是否在某个时间段内
/**
* 判断当前日期是否在某个时间段内
*
* @param nowTime
* @param startTime
* @param endTime
* @return
*/
@Override
public boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
if (nowTime.getTime() == startTime.getTime()
|| nowTime.getTime() == endTime.getTime()) {
return true;
}
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(startTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
判断当前的时间在某一个时段内
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// 获取代金券
LambdaQueryWrapper<VoucherEntity> voucherEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
// SELECT * from act_voucher WHERE now() > start_time AND NOW() < end_time ORDER BY end_time DESC , price DESC
voucherEntityLambdaQueryWrapper
.le(VoucherEntity::getStartTime, format.format(now))
.ge(VoucherEntity::getEndTime, format.format(now))
.orderByDesc(VoucherEntity::getEndTime)
.orderByDesc(VoucherEntity::getPrice)
;
VoucherEntity voucherEntity = voucherService.list(voucherEntityLambdaQueryWrapper).get(0);
System.out.println("voucherEntity = " + voucherEntity);
vue中引入另一个页面
1、按钮页面
1、引用
import VoucherGive from './vouchergive.vue'
2、 组件
components: {
VoucherGive,
},
3、div<>
<VoucherGive
v-if="voucherGive"
ref="voucherGive" # 子组件 链接 父组件调用子组件的方法
@refreshDataList="getDataList" #调用父类中的方法
></VoucherGive>
4、return
data() {
return {
voucherGive: false,
};
},
5、方法
addOrUpdateHandleVoucher() {
this.voucherGive = true;
this.$nextTick(() => {
this.$refs.voucherGive.init(); # init 引用父类中的方法
});
},
6、点击按钮
<el-button type="primary" @click="addOrUpdateHandleVoucher()">发放优惠卷</el-button>
2、展示页
methods: {
init () {
this.visible = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
// 获取代金券列表
// 获取用户
this.$http({
url: this.$http.adornUrl('/carhailing/tbuser/list'),
method: 'get',
params: this.$http.adornParams({
'page': 1,
'limit': 10000000,
})
}).then(({data}) => {
this.userList = data.page.list;
console.log(data.page.list);
this.loading = false;
})
})
},
}
3、展示页全部展示
<template>
<el-dialog
:title="!dataForm.id ? '新增' : '修改'"
:close-on-click-modal="false"
:visible.sync="visible">
<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
<el-form-item label="代金券ID" prop="voucherId">
<el-input v-model="dataForm.voucherId" placeholder="代金券ID"></el-input>
</el-form-item>
<el-form-item label="用户ID" prop="userId">
<!-- <el-input v-model="dataForm.userId" placeholder="用户ID"></el-input> -->
<el-select
v-model="dataForm.userId"
filterable
reserve-keyword
placeholder="用户手机号"
>
<el-option
v-for="item in userList"
:key="item.userId"
:label="item.mobile"
:value="item.userId">
</el-option>
</el-select>`
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
data () {
return {
visible: false,
dataForm: {
voucherId: '',
userId: '',
},
dataRule: {
voucherId: [
{ required: true, message: '代金券ID不能为空', trigger: 'blur' }
],
userId: [
{ required: true, message: '用户ID不能为空', trigger: 'blur' }
],
},
userList: [],
loading: false,
}
},
methods: {
init () {
this.visible = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
// 获取代金券列表
// 获取用户
this.$http({
url: this.$http.adornUrl('/carhailing/tbuser/list'),
method: 'get',
params: this.$http.adornParams({
'page': 1,
'limit': 20,
})
}).then(({data}) => {
this.userList = data.page.list;
console.log(data.page.list);
this.loading = false;
})
})
},
searchUser(query) {
console.log(query);
if (query !== '') {
this.loading = true;
// this.$http({
// url: this.$http.adornUrl('/carhailing/tbuser/list'),
// method: 'get',
// params: this.$http.adornParams({
// 'page': 1,
// 'limit': 20,
// 'mobile': query
// })
// }).then(({data}) => {
// console.log(data);
// this.loading = false;
// })
} else {
this.userList = [];
}
},
// 表单提交
dataFormSubmit () {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
this.$http({
url: this.$http.adornUrl(`/carhailing/voucherreceivetrack/save`),
method: 'post',
data: this.$http.adornData({
'id': this.dataForm.id || undefined,
'voucherId': this.dataForm.voucherId,
'userId': this.dataForm.userId,
})
}).then(({data}) => {
if (data && data.code === 0) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.visible = false
this.$emit('refreshDataList')
}
})
} else {
this.$message.error(data.msg)
}
})
}
})
}
}
}
</script>
获取JSON数据 一级 二级 数据
public void messageArrived(String topic, MqttMessage message) throws Exception {
// 表示JSON 数据 ----> {"data":[{"point":[{"value":3.617,"id":"1"},{"value":6322,"id":"2"}],"tp":1676338704000}]}
String str = new String(message.getPayload());
JSONObject jsonObject = new JSONObject(str);
System.out.println("jsonObject = " + jsonObject);
JSONArray JsonData = jsonObject.getJSONArray("data"); // 一级
for (int i = 0; i < JsonData.length(); i++) { // 获取 data 中的二级信息
JSONObject jsonTwo = JsonData.getJSONObject(i);
String tp = jsonTwo.getString("tp");
System.out.println("tp = " + tp);
JSONArray JsonPoint = jsonTwo.getJSONArray("point");
for (int j = 0; j < JsonPoint.length(); j++) {
JSONObject jsonThree = JsonPoint.getJSONObject(j);
String id = jsonThree.getString("id");
String value = jsonThree.getString("value");
System.out.println("id = " + id + " ,value = " + value);
}
}
}
JSON数据
数据库转化时间格式
date_format(ut.create_time,'%Y-%m-%d') BETWEEN #{startTime} and #{endTime}
<select id="listAll" resultType="io.renren.modules.carhailing.entity.OrderEntity">
select id, order_num, order_type, car_type, user_id, driver_id, start_points, start_points_coord, end_points, end_points_coord, status, distance, fee, duration, reserve_time, start_time, end_time, create_time, delete_flag, version, trade_type, call_phone, pay_status, passenger_name, user_evaluate_id, driver_evaluate_id, order_channel, retreat_reason, retreat_note, voucher_price, accounts_payable
from act_order
<where>
<if test="key != null and key != ''">and order_type like concat('%',#{key},'%')</if>
<if test="carTypety != null and carTypety != -1">and car_type=#{carTypety}</if>
<if test="orderId != null and orderId != ''">and order_num=#{orderId}</if>
and date_format(create_time,'%Y-%m-%d') BETWEEN #{startTime} and #{endTime}
</where>
</select>
路由跳转
index.js 路由的主入口
{
path: '/thmyactivitiesone',
component: resolve =>
import('@/views/modules/cmcconlineshopping/thmyactivities-one.vue'),
name: 'thmyactivitiesone',
meta: { title: 'thmyactivitiesone' }
},
需要跳转页的方法
// 页面中需要跳转的位置
<el-table-column
prop="orderId"
header-align="center"
align="center"
label="订单ID"
>
<template slot-scope="scope">
<el-tag
size="medium"
type="success"
style="color: #96db6c"
@click="toOrderSkip(scope.row.orderId)"
>{{ scope.row.orderId }}</el-tag
>
</template>
</el-table-column>
methods: {
toOrderSkip(orderId) {
this.$router.push({
path: "/orderSkip",
query: {
orderId: orderId,
},
});
},
}
需要跳转页
activated() {
if (
this.$route.query.orderId != null &&
this.$route.query.orderId != undefined
) {
this.dataForm.orderId = this.$route.query.orderId
}
this.getDataList();
},
查询 当天/一周/一个月/三个月/半年/一年的 订单
SELECT
year(CURDATE()) as "年",
MONTH(CURDATE()) as "月",
MONTH(DATE_ADD(NOW(),INTERVAL -6 MONTH)) as "当前月份减少6个月",
DAY(CURDATE()) AS "当前的天数" ,
MONTH(DATE_ADD(NOW(),INTERVAL -3 MONTH)) AS "查询减少三个月的",
DAYOFYEAR(CURDATE()) AS "当前日期是本年的第几天" ,
DATE_ADD(NOW(),INTERVAL -7 day) ,
date_format(DATE_ADD(NOW(),INTERVAL -7 day),'%Y-%m-%d') AS "当前的日期 -7 天是多少号",
DAYOFYEAR(CURDATE()) AS "当前的日期是本年的多少天",
DAYOFYEAR(date_format(DATE_ADD(NOW(),INTERVAL -7 day),'%Y-%m-%d')) AS "当前的日期是本年的多少天 -7" FROM DUAL
# 查询当天的订单
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE()) AND date_format(end_time,'%d') = DAY(CURDATE())
# 查询近一周 MONTH(CURDATE()) 当前月 MONTH(DATE_ADD(NOW(),INTERVAL -3 MONTH)) 当前月减少3个月
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE())
and DAYOFYEAR(end_time) BETWEEN DAYOFYEAR(date_format(DATE_ADD(NOW(),INTERVAL -7 day),'%Y-%m-%d')) AND DAYOFYEAR(CURDATE())
# 查询一个月的订单 (本年的本月)
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE()) and date_format(end_time,'%m') = MONTH(CURDATE())
# 查询进三个月的订单 MONTH(CURDATE()) 当前月 MONTH(DATE_ADD(NOW(),INTERVAL -3 MONTH)) 当前月减少3个月
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE())
and date_format(end_time,'%m') BETWEEN MONTH(DATE_ADD(NOW(),INTERVAL -3 MONTH)) AND MONTH(CURDATE())
# 查询进半年的订单 MONTH(CURDATE()) 当前月 MONTH(DATE_ADD(NOW(),INTERVAL -6 MONTH)) 当前月减少6个月
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE())
and date_format(end_time,'%m') BETWEEN MONTH(DATE_ADD(NOW(),INTERVAL -6 MONTH)) AND MONTH(CURDATE())
# 查询一年的订单
SELECT * FROM act_order where date_format(end_time,'%Y') = year(CURDATE())
vue路由跳转
index.js 路由的主入口
{
path: '/orderSkip',
component: resolve =>
import('@/views/modules/carhailing/order.vue'), # 需要跳转的页
name: 'orderSkip',
meta: { title: 'orderSkip' }
},
优惠卷使用记录 跳转订单
// 页面中需要跳转的位置
<el-table-column
prop="orderId"
header-align="center"
align="center"
label="订单ID"
>
<template slot-scope="scope">
<el-tag
size="medium"
type="success"
style="color: #96db6c"
@click="toOrderSkip(scope.row.orderId)"
>{{ scope.row.orderId }}</el-tag
>
</template>
</el-table-column>
methods: {
toOrderSkip(orderId) {
this.$router.push({
path: "/orderSkip",
query: { // 传递的参数
orderId: orderId,
},
});
},
}
查询数据 page
订单
activated() {
if (
this.$route.query.orderId != null &&
this.$route.query.orderId != undefined
) {
this.dataForm.orderId = this.$route.query.orderId // 接收参数
}
this.getDataList();
},
Controller
/**
* 获取用户的定订单列表
*/
@ApiOperation(value = "获取用户的定订单列表")
@PostMapping("/userOrder")
public R userOrder(@RequestParam Map<String, Object> params, HttpServletRequest request) {
System.out.println("params = " + params);
String userId = jwtUtils.getUserId(request);
// 根据用户id查询订单
PageUtils page = orderService.orderInfo(params, userId);
return R.ok().put("page",page);
}
Service
/**
* 获取用户的订单
*/
PageUtils orderInfo(Map<String, Object> params,String userId);
/**
* 获取用户的订单
*/
@Override
public PageUtils orderInfo(Map<String, Object> params,String userId) {
IPage<OrderEntity> page = this.page(
new Query<OrderEntity>().getPage(params),
new QueryWrapper<OrderEntity>()
);
return new PageUtils(baseMapper.orderInfo(page,params,userId));
}
Dao
IPage<OrderVO> orderInfo(IPage<OrderEntity> page,@Param("params")Map<String, Object> params, @Param("userId")String userId);
<select id="orderInfo" resultType="io.renren.wx.vo.OrderVO">
select
ao.*,
ad.*,
adaa.*
FROM act_order AS ao
LEFT JOIN act_driver AS ad ON ad.id = ao.driver_id
LEFT JOIN act_order_destination_address_alter AS adaa ON adaa.order_id = ao.id
<where>
<if test="userId != null and userId != ''">and ao.user_id=#{userId}</if>
</where>
</select>
BigDecimal 数据处理
java中比较两个日期的大小的所有方式
传递参数的几种方式
方式一:?号传参
@RequestMapping("/two")
public R two(@RequestParam Map<String,Object> params){ // get请求时候 ?问号传参
// post请求 就是param传递参数 form-data
form-data --> 1、chekbox --> 多选 表单
2、fill --> 文件
方式二: json的方式传递参数
@PostMapping("voucherUse")
public R voucherUse(@RequestBody Map<String, String> params) { // json的方式传递参数
方式三:restult
@GetMapping("/test/{id}")
@ResponseBody
public String coordinateInfo(@PathVariable("id") Long id){ // restult
return "你好啊" + id ;
}
logback.xml 生成日志 位置resource 下
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>
Vue封装组件
import request from '@/utils/request'
// 查询食品台账列表
export function listFood_account(query) {
return request({
url: '/food/food_account/list',
method: 'get',
params: query
})
}
// 查询食品台账详细
export function getFood_account(id) {
return request({
url: '/food/food_account/' + id,
method: 'get'
})
}
// 新增食品台账
export function addFood_account(data) {
return request({
url: '/food/food_account',
method: 'post',
data: data
})
}
// 修改食品台账
export function updateFood_account(data) {
return request({
url: '/food/food_account',
method: 'put',
data: data
})
}
// 删除食品台账
export function delFood_account(id) {
return request({
url: '/food/food_account/' + id,
method: 'delete'
})
}
实体类中可拓展的Dao类想实现MyBatisPlus
仿照实体类编写MyBatis Plus内容
/**
* 基础服务接口,所有Service接口都要继承
*
* @author Mark sunlightcs@gmail.com
*/
public interface BaseService<T> {
Class<T> currentModelClass();
/**
* <p>
* 插入一条记录(选择字段,策略插入)
* </p>
*
* @param entity 实体对象
*/
boolean insert(T entity);
/**
* <p>
* 插入(批量),该方法不支持 Oracle、SQL Server
* </p>
*
* @param entityList 实体对象集合
*/
boolean insertBatch(Collection<T> entityList);
/**
* <p>
* 插入(批量),该方法不支持 Oracle、SQL Server
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 插入批次数量
*/
boolean insertBatch(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 选择修改
* </p>
*
* @param entity 实体对象
*/
boolean updateById(T entity);
/**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param entity 实体对象
* @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);
/**
* <p>
* 根据ID 批量更新
* </p>
*
* @param entityList 实体对象集合
*/
boolean updateBatchById(Collection<T> entityList);
/**
* <p>
* 根据ID 批量更新
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 更新批次数量
*/
boolean updateBatchById(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
*/
boolean deleteById(Serializable id);
/**
* <p>
* 删除(根据ID 批量删除)
* </p>
*
* @param idList 主键ID列表
*/
boolean deleteBatchIds(Collection<? extends Serializable> idList);
T getOne(Wrapper<T> T);
}
/**
* 基础服务类,所有Service都要继承
*
* @author Mark sunlightcs@gmail.com
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements BaseService<T> {
@Autowired
protected M baseDao;
protected Log log = LogFactory.getLog(getClass());
/**
* 获取分页对象
* @param params 分页查询参数
* @param defaultOrderField 默认排序字段
* @param isAsc 排序方式
*/
protected IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
//分页参数
long curPage = 1;
long limit = 10;
if(params.get(Constant.PAGE) != null){
curPage = Long.parseLong((String)params.get(Constant.PAGE));
}
if(params.get(Constant.LIMIT) != null){
limit = Long.parseLong((String)params.get(Constant.LIMIT));
}
//分页对象
Page<T> page = new Page<>(curPage, limit);
//分页参数
params.put(Constant.PAGE, page);
//排序字段
String orderField = (String)params.get(Constant.ORDER_FIELD);
String order = (String)params.get(Constant.ORDER);
//前端字段排序
if(StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)){
if(Constant.ASC.equalsIgnoreCase(order)) {
return page.addOrder(OrderItem.asc(orderField));
}else {
return page.addOrder(OrderItem.desc(orderField));
}
}
//没有排序字段,则不排序
if(StringUtils.isBlank(defaultOrderField)){
return page;
}
//默认排序
if(isAsc) {
page.addOrder(OrderItem.asc(defaultOrderField));
}else {
page.addOrder(OrderItem.desc(defaultOrderField));
}
return page;
}
protected <T> PageData<T> getPageData(List<?> list, long total, Class<T> target){
List<T> targetList = ConvertUtils.sourceToTarget(list, target);
return new PageData<>(targetList, total);
}
protected <T> PageData<T> getPageData(IPage page, Class<T> target){
return getPageData(page.getRecords(), page.getTotal(), target);
}
protected void paramsToLike(Map<String, Object> params, String... likes){
for (String like : likes){
String val = (String)params.get(like);
if (StringUtils.isNotBlank(val)){
params.put(like, "%" + val + "%");
}else {
params.put(like, null);
}
}
}
/**
* <p>
* 判断数据库操作是否成功
* </p>
* <p>
* 注意!! 该方法为 Integer 判断,不可传入 int 基本类型
* </p>
*
* @param result 数据库操作返回影响条数
* @return boolean
*/
protected static boolean retBool(Integer result) {
return SqlHelper.retBool(result);
}
protected Class<M> currentMapperClass() {
return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0);
}
@Override
public Class<T> currentModelClass() {
return (Class<T>)ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1);
}
protected String getSqlStatement(SqlMethod sqlMethod) {
return SqlHelper.getSqlStatement(this.currentMapperClass(), sqlMethod);
}
@Override
public boolean insert(T entity) {
return BaseServiceImpl.retBool(baseDao.insert(entity));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean insertBatch(Collection<T> entityList) {
return insertBatch(entityList, 100);
}
/**
* 批量插入
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean insertBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}
/**
* 执行批量操作
*/
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer);
}
@Override
public boolean updateById(T entity) {
return BaseServiceImpl.retBool(baseDao.updateById(entity));
}
@Override
public boolean update(T entity, Wrapper<T> updateWrapper) {
return BaseServiceImpl.retBool(baseDao.update(entity, updateWrapper));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateBatchById(Collection<T> entityList) {
return updateBatchById(entityList, 30);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateBatchById(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
sqlSession.update(sqlStatement, param);
});
}
@Override
public T selectById(Serializable id) {
return baseDao.selectById(id);
}
@Override
public boolean deleteById(Serializable id) {
return SqlHelper.retBool(baseDao.deleteById(id));
}
@Override
public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
}
@Override
public T getOne(Wrapper<T> T) {
return baseDao.selectOne(T);
}
}
@PostMapping("officialLogin")
@ApiOperation("公众号登录")
public Result officialLogin(@RequestBody NewlyInsuredDTO newlyInsuredDTO){
System.out.println("newlyInsuredDTO = " + newlyInsuredDTO);
String name = newlyInsuredDTO.getName();
String idNumber = newlyInsuredDTO.getIdNumber();
// LambdaQueryWrapper<NewlyInsuredEntity> queryWrapper = new LambdaQueryWrapper<>();
// queryWrapper.eq(NewlyInsuredEntity::getName, name);
// NewlyInsuredEntity newlyInsuredEntity = newlyInsuredService.getOne(queryWrapper);
// System.out.println("newlyInsuredEntity = " + newlyInsuredEntity);
NewlyInsuredEntity newlyInsuredEntity = newlyInsuredService.nameAndIdNumber(name);
if (newlyInsuredEntity == null ) {
return new Result().error("用户名不存在");
}
// 判断身份证是否一致
if (!newlyInsuredEntity.getIdNumber().equals(idNumber)){
return new Result().error("身份证输入不正确");
}
//获取登录token
TokenEntity tokenEntity = tokenService.createToken(Long.parseLong(idNumber));
System.out.println("tokenEntity = " + tokenEntity);
Map<String, Object> map = new HashMap<>(1);
map.put("token", tokenEntity);
return new Result().ok(map);
}
导出excel功能
方式一:renren
后端
package io.renren.modules.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0 2023-02-23
*/
@Data
@ApiModel(value = "")
public class NewlyInsuredDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "参保记录主键")
private Long id;
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "证件类型")
private String idDocument;
@ApiModelProperty(value = "身份证件号码")
private String idNumber;
@ApiModelProperty(value = "性别")
private Integer sex;
@ApiModelProperty(value = "联系电话")
private String phone;
@ApiModelProperty(value = "户籍所在地(居 住证登记地)")
private String domicile;
@ApiModelProperty(value = "村(社区)")
private String community;
@ApiModelProperty(value = "通讯地址")
private String mailingAddress;
@ApiModelProperty(value = "申请人身份")
private Integer applicant;
@ApiModelProperty(value = "申请人身份内容")
private String applicantContent;
@ApiModelProperty(value = "财政补助对象")
private Integer financialAssistance;
@ApiModelProperty(value = "财政补助对象内容")
private String financialAssistanceContent;
@ApiModelProperty(value = "申请人或监护人")
private String guardian;
@ApiModelProperty(value = "收件审核")
private String receiptAudit;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "备注")
private String remarks;
@ApiModelProperty(value = "用户主键")
private Long userId;
@ApiModelProperty(value = "部门主键")
private Long deptId;
@ApiModelProperty(value = "删除状态")
private Integer delState;
@ApiModelProperty(value = "图片地址")
private String imgUrl;
@ApiModelProperty(value = "文件地址")
private String fileUrl;
@ApiModelProperty(value = "审核状态")
private Integer state;
}
@GetMapping("export")
@ApiOperation("导出")
@LogOperation("导出")
@RequiresPermissions("modules:newlyinsured:export")
public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<NewlyInsuredDTO> list = newlyInsuredService.list(params);
ExcelUtils.exportExcelToTarget(response, null, list, NewlyInsuredExcel.class);
}
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* excel工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class ExcelUtils {
/**
* Excel导出
*
* @param response response
* @param fileName 文件名
* @param list 数据List
* @param pojoClass 对象Class
*/
public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
Class<?> pojoClass) throws IOException {
if(StringUtils.isBlank(fileName)){
//当前日期
fileName = DateUtils.format(new Date());
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, list);
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
}
/**
* Excel导出,先sourceList转换成List<targetClass>,再导出
*
* @param response response
* @param fileName 文件名
* @param sourceList 原数据List
* @param targetClass 目标对象Class
*/
public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
Class<?> targetClass) throws Exception {
List targetList = new ArrayList<>(sourceList.size());
for(Object source : sourceList){
Object target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
targetList.add(target);
}
exportExcel(response, fileName, targetList, targetClass);
}
}
前端
<el-form-item>
<el-button type="primary" @click="Export()">导出</el-button>
</el-form-item>
Export(row) {
this.$http.get(`/modules/newlyinsured/Export`, {
params: {
...this.dataForm
}
}).then(({ data: res }) => {
if (res.code !== 0) {
return this.$message.error(res.msg)
}
if (res.code !== 1) {
this.$message.success("导出成功")
this.wordUrl=res.data
this.downloadModel()
}
}).catch(() => {})
},
方式二:easyExcel
后端
package io.renren.modules.modules.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
/**
* 参保人员信息表
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0 2023-03-13
*/
@HeadRowHeight(20)//表头高度
@ContentRowHeight(20)//内容的行高
@Data
@TableName("s_headcount")
public class HeadcountEntity {
/**
* 人员主键
*/
@ExcelIgnore
private Long id;
/**
* 成员姓名
*/
@ExcelProperty(value = {"人员信息","成员姓名"},index = 0)
private String name;
/**
* 证件号
*/
@ColumnWidth(25)
@ExcelProperty(value = {"人员信息","证件号"},index = 2)
private String idNumber;
/**
* 性别
*/
@ExcelProperty(value = {"人员信息","性别"} ,index = 3)
private Integer sex;
/**
* 年龄
*/
@ExcelProperty(value = {"人员信息","年龄"},index = 4)
private Integer age;
/**
* 证件类型
*/
@ExcelProperty(value = {"人员信息","证件类型"},index = 1)
@ColumnWidth(15)
private String idDocument;
/**
* 手机号码
*/
@ColumnWidth(15)
@ExcelProperty(value = {"人员信息","手机号码"},index = 5)
private String phone;
/**
* 参保状态
*/
@ExcelIgnore
private Integer insuredStatus;
/**
* 参保状态 Name
*/
@ExcelProperty(value = {"人员信息","参保状态"},index = 6)
@TableField(exist = false)
@ColumnWidth(15)
private String insuredStatusName;
/**
* 申请类别
*/
@ExcelIgnore
private Integer insuredApplication;
/**
* 申请类别
*/
@ExcelProperty(value = {"人员信息","申请类别"},index = 7)
@ColumnWidth(15)
@TableField(exist = false)
private String insuredApplicationName;
/**
* 参保人员类别
*/
@ExcelIgnore
private Integer insuredCategory;
/**
* 创建时间
*/
@ExcelIgnore
private Date createTime;
/**
* 更新时间
*/
@ColumnWidth(25)
@ExcelProperty(value = {"人员信息","更新时间"},index = 8)
@DateTimeFormat("yyyy-MM-dd HH-mm-ss")
private Date updateTime;
/**
* 户主姓名
*/
@ExcelProperty(value = {"人员信息","户主姓名"},index = 9)
@ColumnWidth(15)
private String householder;
/**
* 开始时间
*/
@ExcelIgnore
private Date startTime;
/**
* 结束时间
*/
@ExcelIgnore
private Date endTime;
/**
* 救助身份对象
*/
@ExcelIgnore
private Integer salvageStatus;
/**
* 用户主键
*/
@ExcelIgnore
private Long userId;
/**
* 部门主键
*/
@ExcelIgnore
private Long deptId;
/**
* 所属社区
*/
@ExcelIgnore
private String community;
/**
* 备注
*/
@ColumnWidth(25)
@ExcelProperty(value = {"人员信息","备注"},index = 12)
private String remarks;
/**
* 删除状态
*/
@ExcelIgnore
private Integer delState;
/**
* 乡
*/
@ColumnWidth(15)
@ExcelProperty(value = {"人员信息","乡"},index = 10)
private String township;
/**
* 村
*/
@ColumnWidth(15)
@ExcelProperty(value = {"人员信息","村"},index = 11)
private String village;
public HeadcountEntity() {
}
/**
* @param name 成员姓名
* @param idNumber 证件号
* @param sex 性别
* @param phone 手机号码
* @param createTime 创建时间
* @param updateTime 更新时间
* @param userId 用户主键
* @param deptId 部门主键
* @param remarks 备注
* @param village 村
*/
public HeadcountEntity(
String name, String idNumber, Integer sex, String phone,Date createTime, Date updateTime,Long userId, Long deptId, String remarks, String village) {
this.name = name;
this.idNumber = idNumber;
this.sex = sex;
this.phone = phone;
this.createTime = createTime;
this.updateTime = updateTime;
this.userId = userId;
this.deptId = deptId;
this.remarks = remarks;
this.village = village;
}
}
@GetMapping("excel")
@ResponseBody
public void execl(HttpServletResponse response,@RequestParam Map<String, Object> params) throws Exception {
System.out.println("params = " + params);
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 工作簿对象
ServletOutputStream outputStream = response.getOutputStream();
ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, HeadcountEntity.class);
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("人员信息", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
// 工作表对象
ExcelWriterSheetBuilder sheet = writeWorkBook.sheet("人员信息");
// 姓名 证件号 手机号 乡村 参保状态 申请类别
// name=12312, idNumber=12312, phone=12312, township=12312, insuredStatus=1, insuredApplication=1,
QueryWrapper<HeadcountEntity> headcountEntityQueryWrapper = new QueryWrapper<>();
headcountEntityQueryWrapper.eq("name", params.get("name")).or()
.eq("id_number",params.get("idNumber")).or()
.eq("phone",params.get("phone")).or()
.eq("township",params.get("township")).or()
.eq("insured_status",params.get("insuredStatus")).or()
.eq("insured_application",params.get("insuredApplication"));
List<HeadcountEntity> headcountEntities = headcountService.selectList(headcountEntityQueryWrapper);
System.out.println("headcountEntities = " + headcountEntities);
// 参保状态
List<SysDictDataEntity> insuredStatusList = sysDictDataService.queryByDictId("insuredStatus");
// 申请类别
List<SysDictDataEntity> categoryApplicationList = sysDictDataService.queryByDictId("categoryApplication");
for (int i = 0; i < headcountEntities.size(); i++) {
headcountEntities.get(i).setIdDocument("身份证");
for (SysDictDataEntity sysDictDataEntity : insuredStatusList) {
if (sysDictDataEntity.getDictValue().equals(String.valueOf(headcountEntities.get(i).getInsuredStatus()))){
headcountEntities.get(i).setInsuredStatusName(sysDictDataEntity.getDictLabel());
}
}
for (SysDictDataEntity sysDictDataEntity : categoryApplicationList) {
if (sysDictDataEntity.getDictValue().equals(String.valueOf(headcountEntities.get(i).getInsuredApplication()))){
headcountEntities.get(i).setInsuredApplicationName(sysDictDataEntity.getDictLabel());
}
}
}
// 写
sheet.doWrite(headcountEntities);
}
前端
<el-form-item>
<el-button size="small" type="primary" @click="excel">人员信息导出</el-button>
</el-form-item>
excel() {
let DCfrom = {
name: this.dataForm.name,
idNumber: this.dataForm.idNumber,
phone: this.dataForm.phone,
township: this.dataForm.township,
insuredStatus: this.dataForm.insuredStatus,
insuredApplication: this.dataForm.insuredApplication,
};
console.log(DCfrom);
this.$http
.get(`/modules/headcount/excel`, {
params: DCfrom,
responseType: "blob",
})
.then(({ data: res }) => {
const blob = new Blob([res]);
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = "人员信息.xlsx"; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})
.catch(() => {});
},
StringUtils.hasText(字符串)的作用
如果里面的值为null,“”," ",那么返回值为false;否则为true
String截取文件路径
System.out.println("file = " + file); // file = /profile/upload/2023/07/05/上机考核试题(2023) - 副本_20230705091438A001.doc
TdFiles tdFiles = new TdFiles();
tdFiles.setId(IdUtils.randomUUID());
tdFiles.setName(file.substring(file.lastIndexOf("/") + 1,file.lastIndexOf(".")));
tdFiles.setDataId(tdReimbursement.getId());
// 文件名称
tdFiles.setFileName(file.substring(file.lastIndexOf("/") + 1,file.lastIndexOf(".")));
// 文件路径
tdFiles.setFilePath(file.substring(0,file.lastIndexOf("/") + 1));
// 制定的后缀
tdFiles.setFileType(file.substring(file.lastIndexOf(".")));
tdFiles.setOperateTime(new Date());
tdFiles.setUserId(tdReimbursement.getUserId());
时间选择器限制选择日期
<el-form-item label="填写日期" prop="reportDate">
<el-date-picker clearable
v-model="form.reportDate"
type="datetime"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择填写日期"
:picker-options="pickerOptions"
>
</el-date-picker>
</el-form-item>
// 限制日期选择器
pickerOptions: {
disabledDate(time) {
return time.getTime() > Date.now() - 8.64e6
}
},
Vue 文件下载
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
类路径 @RequestMapping("/system/reimbursement")
# 实体类
@RequestMapping("/clickFiledownLoad")
public String clickFiledownLoad(@RequestParam Map<String, Object> params, HttpServletResponse response) {
String caseVideos = String.valueOf(params.get("caseVideos"));
String localPath = RuoYiConfig.getProfile();
// 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(caseVideos, Constants.RESOURCE_PREFIX);
// 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
if (downloadName != null) {
//设置文件路径
System.out.println("downloadPath = " + downloadPath);
File file = new File(downloadPath);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + downloadName);// 设置文件名
response.setContentLength((int) file.length());
byte[] buffer = new byte[1024];
ByteArrayInputStream bis = null;
try {
//文件转成字节流
byte[] bytes = FileUtil.readBytes(file);
bis = new ByteArrayInputStream(bytes);
OutputStream os = response.getOutputStream();
int len;
while ((len = bis.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally { // 做关闭操作
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
// 组件多附件遍历
<el-table-column
prop="file"
header-align="center"
align="center"
label="附件"
width="230px"
>
<template slot-scope="scope">
<el-tag effect="plain" v-for="(item ,i) in String(scope.row.file).split(',')" v-if="scope.row.file" ><a
@click="clickFile(item)" ><span>{{ getFileNames(item) }}</span></a></el-tag>
<!-- <el-tag-->
<!-- size="medium"-->
<!-- type="success"-->
<!-- style="color: #96db6c"-->
<!-- @click="handleDownload(scope.row.file)"-->
<!-- >{{ fragment(scope.row.file) }}</el-tag>-->
</template>
</el-table-column>
// 按钮附件详情
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="toOrderSkip(scope.row.id)"
>附件详情
</el-button>
// 引入
import {
clickFiles
} from '@/api/system/reimbursement'
// 方法
getFileNames(regulationsFiles){
return regulationsFiles.substring(regulationsFiles.lastIndexOf("/")+1)
},
// 文件下载
clickFile(path) {
// this.$download.name(path, false);
const index = path.lastIndexOf('\/')
const name = path.substring(index + 1)
let params = {'caseVideos': path}
clickFiles(params).then(res => {
if (res != null) {
let url = window.URL.createObjectURL(new Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', name)
// 指定下载后的文件名,防跳转
document.body.appendChild(link)
link.click()
} else {
this.$modal.msgError('下载失败,文件不存在')
}
})
// this.$http({
// url: process.env.VUE_APP_BASE_API + "/system/reimbursement/clickFiledownLoad",
// method: 'get',
//
// headers: {'Authorization': Authorization},
// responseType: 'blob'
// }).then(res => {
// if (res.data != null) {
// let url = window.URL.createObjectURL(new Blob([res.data]))
// let link = document.createElement('a')
// link.style.display = 'none'
// link.href = url
// link.setAttribute('download', name)
// // 指定下载后的文件名,防跳转
// document.body.appendChild(link)
// link.click()
// } else {
// this.$modal.msgError('下载失败,文件不存在')
// }
// }).catch(function (error) {
// console.log(error)
// })
},
// 查询报销记录基本信息列表
export function clickFiles(query) {
return request({
url: '/system/reimbursement/clickFiledownLoad',
method: 'get',
params: query,
responseType: 'blob'
})
}