package org.springnewfiber.dataadapter.sswj.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.http.ContentType; import cn.hutool.http.Header; import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelWriter; import com.baomidou.mybatisplus.core.toolkit.StringPool; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springnewfiber.dataadapter.sswj.entity.TableColumnInfo; import org.springnewfiber.dataadapter.sswj.mapper.ExcelPlusMapper; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @program: newfiber-data-adapter * @description: * @author: djt * @create: 2022-05-18 11:14 **/ @Service @AllArgsConstructor public class ExcelPlusServiceImpl { private final ExcelPlusMapper excelPlusMapper; public void exportExcel(String dataName, String tableName, HttpServletResponse response, String lastSql) throws IOException { List<TableColumnInfo> columnInfoList = excelPlusMapper.selectTableColumn(dataName, tableName); String tableNameComment = excelPlusMapper.selectTableName(dataName, tableName); if (CollUtil.isEmpty(columnInfoList)) { throw new RuntimeException("数据不存在"); } ExcelWriter writer = ExcelUtil.getWriter(); Map<String, String> headMap = columnInfoList.stream().collect(Collectors.toMap(TableColumnInfo::getColumnName, TableColumnInfo::getCloumnTitle)); writer.setHeaderAlias(headMap); excelPlusMapper.selectDataByTableName(tableName, lastSql).forEach(i -> { if (writer.getRowCount() == 1) { writer.writeRow(i, true); } else { writer.writeRow(i, false); } }); if (StringUtils.isNotBlank(tableNameComment)) { writer.renameSheet(tableNameComment.concat(StringPool.DASH).concat(lastSql == null ? StringPool.EMPTY : lastSql)); } else { writer.renameSheet(tableName.concat(StringPool.DASH).concat(lastSql == null ? StringPool.EMPTY : lastSql)); } response.setContentType(ContentType.MULTIPART.getValue()); String fileName=new String(URLEncoder.encode(StringUtils.isNotBlank(tableNameComment)?tableNameComment.concat(StringPool.LEFT_SQ_BRACKET).concat(tableName).concat(StringPool.RIGHT_SQ_BRACKET):tableName, "utf-8")); // response.addHeader(Header.CONTENT_DISPOSITION.getValue(), "attachment;filename=" .concat( URLEncoder.encode(StringUtils.isNotBlank(tableNameComment)?tableNameComment:tableName.concat(".xls"), "utf-8"))); response.addHeader(Header.CONTENT_DISPOSITION.getValue(), "attachment;filename=" .concat(fileName).concat(".xls")); ServletOutputStream out = response.getOutputStream(); writer.flush(out, true); writer.close(); IoUtil.close(out); } }