1.在日常开发的需求中,有可能会遇到,导出的excel文件设置密码,发送给别人后,输入密码才能打开,怎么处理呢,上代码。(若依自带的ExcelUtil)
(1).前端代码,定义一个用户导出时候导出的字段数组,
selectedFields: [], // 用户选择的字段
exportFields: [{ key: 'Name', label: '名称' },]//设置所有导出的字段,可以在加载时候直接将数据加载进去,或者直接设置页面导出字段的key和label,
(2).界面提示输入导出的密码,选取导出的格式,设置打开时候的密码。
{{ field.label }}
(3).点击确定,这里的密码校验我简单的设置成4位字符,你可以自行设置密码规则
handleExport() {
if (this.selectedFields.length === 0) {
this.$message.warning('请选择要导出的字段');
return;
}
this.$prompt('请输入文件打开密码', '密码保护', {
confirmButtonText: '导出',
cancelButtonText: '取消',
inputType: 'password',
inputValidator: (value) => {
if (!value || value.length < 4) {
return '密码至少需要4位字符';
}
}
}).then(({ value }) => {
this.download(
"ruoyi/Export/export",
{
...this.queryParams,
fields: this.selectedFields.join(','),
password: value // 传递密码到后端
},
this.form.wjmc+this.form.dcgs
//设置文件名和文件格式
);
this.openExportDialog = false;
}).catch(() => {
this.$message.info('取消导出');
});
},
(4).后端代码
@PostMapping("/ruoyi/Export/export")
public void exportPassword(HttpServletResponse response, Info info,
@RequestParam(required = false) String fields
,@RequestParam String password) throws IOException, InvalidFormatException {
List list = infoService.queryList(info);
ExcelUtil util = new ExcelUtil<>(Info.class);
util.exportPassword(response, list, "数据", fields, fieldMapping, password);
}
(5).若依自带的ExcelUtil工具类里面添加方法exportPassword
public void exportPassword(HttpServletResponse response, List list,
String title, String fields,
Map fieldMapping,
String password) throws IOException, InvalidFormatException {
// 1. 创建内存中的工作簿
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (SXSSFWorkbook workbook = new SXSSFWorkbook(1000)) {
// 创建工作表(保持原有逻辑)
Sheet sheet = workbook.createSheet(title);
Row titleRow = sheet.createRow(0);
// 获取所有字段
Field[] allFields = this.clazz.getDeclaredFields();
Map fieldMap = new HashMap<>();
for (Field field : allFields) {
fieldMap.put(field.getName(), field);
}
// 创建表头
String[] fieldArray = StringUtils.split(fields, ",");
int colIndex = 0;
for (String fieldName : fieldArray) {
Field field = fieldMap.get(fieldName);
if (field != null) {
Cell cell = titleRow.createCell(colIndex++);
String displayName = fieldMapping.getOrDefault(fieldName, fieldName);
cell.setCellValue(displayName);
}
}
// 填充数据
for (int i = 0; i < list.size(); i++) {
Row row = sheet.createRow(i + 1);
T obj = list.get(i);
colIndex = 0;
for (String fieldName : fieldArray) {
Field field = fieldMap.get(fieldName);
if (field != null) {
field.setAccessible(true);
try {
Cell cell = row.createCell(colIndex++);
Object value = field.get(obj);
cell.setCellValue(value != null ? value.toString() : "");
} catch (IllegalAccessException e) {
}
}
}
}
// 写入内存流
workbook.write(baos);
}
直接复制粘贴就能用 go go go
注意:这里的fieldMapping是导出的字段 ,密码的检验设定在前端就可以,自行设置就行。
有问题请留言!!!