前端:
表格页面
<template>
<view>
<el-button
type="success"
plain
@click="handleExport"
:loading="exportLoading"
class="top-button"
:disabled="multipleSelection.length == 0"
>导出</el-button>
<el-table
:data="tableData"
border
stripe
:cell-style="{ 'text-align': 'center' }"
:header-cell-style="{
background: '#b7babd',
color: '#1e1f22',
height: '35px',
'text-align': 'center'
}"
style="width: 100%"
max-height="600"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" />
<!-- 省略其它列 -->
</el-table>
<Pagination
:total="total"
v-model:page="queryParams.pageNo"
v-model:limit="queryParams.pageSize"
@pagination="init"
/>
</view>
</template>
<script setup lang="ts">
import download from '@/utils/download'
const tableData = ref([])
const total = ref(0) // 列表的总页数
const exportLoading = ref(false) // 导出的加载中
const queryParams = reactive({
pageNo: 1,
pageSize: 10
})
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
multipleSelection.value = val
}
const init = async () => {
loading.value = true
// 获取表格数据
let data = await getAllDataApi(queryParams)
tableData.value = data.list
total.value = data.total
}
const handleExport = async () => {
try {
const ids = multipleSelection.value.map((item) => item.id)
// 导出
exportLoading.value = true
const data = await projectApi.exportProject(ids)
download.excel(data, '导出文件名.xls')
} finally {
exportLoading.value = false
}
}
download.ts文件
const download0 = (data: Blob, fileName: string, mineType: string) => {
// 创建 blob
const blob = new Blob([data], { type: mineType })
// 创建 href 超链接,点击进行下载
window.URL = window.URL || window.webkitURL
const href = URL.createObjectURL(blob)
const downA = document.createElement('a')
downA.href = href
downA.download = fileName
downA.click()
// 销毁超连接
window.URL.revokeObjectURL(href)
}
const download = {
// 下载 Excel 方法
excel: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/vnd.ms-excel')
},
// 下载 Word 方法
word: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/msword')
},
// 下载 Zip 方法
zip: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/zip')
},
// 下载 Html 方法
html: (data: Blob, fileName: string) => {
download0(data, fileName, 'text/html')
},
// 下载 Markdown 方法
markdown: (data: Blob, fileName: string) => {
download0(data, fileName, 'text/markdown')
}
}
export default download
export const export = async (ids) => {
return await request.download({ url: '/url/excel?ids=' + ids })
}
后端:
controller
@GetMapping("/excel")
@Operation(summary = "导出 Excel")
@OperateLog(type = EXPORT)
public void exporClass(@RequestParam("ids") Long[] ids,HttpServletResponse response) throws IOException{
// 将字符串数组转换为 Long 类型数组
List<BaseExcelVO> excelVOS = studentService.exportProject(ids);
ExcelUtils.write(response,"学生信息表导出.xls","学生信息列表"
BaseExcelVO.class, excelVOS );
}
导出的类
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 导出的Excel VO
*/
@Data
public class BaseExcelVO {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("分数")
private BigDecimal score; // BigDecimal 类型计算更精确;
@ExcelProperty("选项内容")
private String options;
}
实现方法
@Override
public List<BaseExcelVO> exportProject(Long[] ids) {
List<BaseExcelVO> excelVOS = new ArrayList<>();
// 通过传入的ids 批量查出数据
List<BaseDO> doList = baseMapper.selectBatchIds(Arrays.asList(ids));
doList.sort(Comparator.comparingLong(BaseDO::getId).reversed());
BaseExcelVO baseExcelVO;
for (CheckBaseProjectDO infoDo : doList) {
baseExcelVO= new BaseExcelVO();
// 逐一赋值
BeanUtils.copyProperties(infoDo, baseExcelVO);
// 查到的数据是:[{index:0,value:AAA},{index:1,value:BBB},{index:2,value:CCC}]
// 想导出为:AAA;BBB;CCC
Gson gson = new Gson(); // 创建了一个Gson对象,处理 JSON 数据的序列化和反序列化
JsonArray jsonArray = gson.fromJson(infoDo.getOptions(), JsonArray.class);
// 构建以分号分隔的字符串
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = jsonArray.get(i).getAsJsonObject();
String value = obj.get("value").getAsString();
resultBuilder.append(value);
// 如果不是最后一个元素,则添加分号
if (i < jsonArray.size() - 1) {
resultBuilder.append(";");
}
}
baseExcelVO.setOptions(resultBuilder.toString());
excelVOS.add(baseExcelVO);
}
return excelVOS;
}