Ver Fonte

完善通用sql,编写导入接口、导出模版。优化导出接口,解析前端回传token携带数据源信息

韩帛霖 há 2 anos atrás
pai
commit
525079bf5a

+ 34 - 3
ruoyi-admin/src/main/java/com/ruoyi/web/controller/dragForm/CommonController.java

@@ -1,18 +1,22 @@
 package com.ruoyi.web.controller.dragForm;
 
 import com.ruoyi.common.annotation.Anonymous;
+import com.ruoyi.common.config.RuoYiConfig;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.AjaxResult;
 import com.ruoyi.common.core.domain.entity.SysUser;
 import com.ruoyi.common.core.domain.model.LoginUser;
 import com.ruoyi.common.core.page.TableDataInfo;
 import com.ruoyi.common.utils.SecurityUtils;
+import com.ruoyi.common.utils.file.FileUploadUtils;
+import com.ruoyi.common.utils.file.FileUtils;
 import com.ruoyi.system.entity.CommonEntity;
 import com.ruoyi.system.entity.TableSql;
 import com.ruoyi.system.service.ICommonService;
 import com.ruoyi.system.service.ITableSqlService;
 import dm.jdbc.filter.stat.util.JSONUtils;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletResponse;
@@ -47,7 +51,7 @@ public class CommonController extends BaseController {
         map.put("tableName", tableName);
         //  df_name
         List<CommonEntity> commonEntities = commonService.selectList(map);
-        commonEntities.forEach(item->{
+        commonEntities.forEach(item -> {
             System.out.println(item.getRetMap());
         });
 
@@ -79,6 +83,12 @@ public class CommonController extends BaseController {
         return toAjax(commonService.batchDelete(map));
     }
 
+    /**
+     * 联合查询通用sql
+     *
+     * @param commonEntity
+     * @return
+     */
     @GetMapping("/getTableList")
     public TableDataInfo queryTableList(CommonEntity commonEntity) {
         TableSql tableSql = iTableSqlService.selectTableSqlByTSqlKey(commonEntity.getFormMap().get("SQLKEY").toString());
@@ -86,9 +96,30 @@ public class CommonController extends BaseController {
         return getDataTable(commonService.queryTableList(commonEntity, tableSql));
     }
 
+    /**
+     * 通用导出excel
+     *
+     * @param response
+     * @param tableName
+     * @param sqlKey
+     * @throws Exception
+     */
     @GetMapping("/export")
-    public void export(HttpServletResponse response,@RequestParam("tableName") String tableName,@RequestParam("sqlKey") String sqlKey) throws Exception {
-        commonService.export(response,tableName,sqlKey);
+    public void export(HttpServletResponse response, @RequestParam("tableName") String tableName, @RequestParam("sqlKey") String sqlKey) throws Exception {
+        commonService.export(response, tableName, sqlKey);
+    }
+
+    /**
+     * 通用导出excel模版
+     *
+     * @param response
+     * @param tableName
+     * @param sqlKey
+     * @throws Exception
+     */
+    @GetMapping("/exportTemplate")
+    public void exportTemplate(HttpServletResponse response, @RequestParam("tableName") String tableName, @RequestParam("sqlKey") String sqlKey) throws Exception {
+        commonService.exportTemplate(response, tableName, sqlKey);
     }
 
 }

+ 247 - 0
ruoyi-admin/src/main/java/com/ruoyi/web/controller/dragForm/CommonFileController.java

@@ -0,0 +1,247 @@
+package com.ruoyi.web.controller.dragForm;
+
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.fastjson2.JSON;
+import com.ruoyi.common.annotation.Anonymous;
+import com.ruoyi.common.annotation.Log;
+import com.ruoyi.common.config.RuoYiConfig;
+import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.common.core.domain.entity.SysUser;
+import com.ruoyi.common.enums.BusinessType;
+import com.ruoyi.common.utils.SecurityUtils;
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.file.FileUploadUtils;
+import com.ruoyi.common.utils.file.FileUtils;
+import com.ruoyi.common.utils.poi.ExcelUtil;
+import com.ruoyi.framework.config.ServerConfig;
+import com.ruoyi.system.entity.CommonEntity;
+import com.ruoyi.system.entity.TableInfo;
+import com.ruoyi.system.service.ICommonService;
+import com.ruoyi.system.service.IDataSourceService;
+import io.lettuce.core.ScriptOutputType;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.models.auth.In;
+import org.apache.poi.ss.formula.functions.T;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.poi.ss.usermodel.*;
+
+import static com.ruoyi.common.core.domain.AjaxResult.success;
+
+/**
+ * 通用请求处理
+ *
+ * @author ruoyi
+ */
+@Anonymous
+@RestController
+@RequestMapping("/common")
+public class CommonFileController {
+    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
+
+    @Autowired
+    private ServerConfig serverConfig;
+
+    @Resource
+    private IDataSourceService dataSourceService;
+
+    @Resource
+    private ICommonService commonService;
+
+    private static final String FILE_DELIMETER = ",";
+
+    /**
+     * 通用下载请求
+     *
+     * @param fileName 文件名称
+     * @param delete   是否删除
+     */
+    @GetMapping("/download")
+    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
+        try {
+            if (!FileUtils.checkAllowDownload(fileName)) {
+                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
+            }
+            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
+            String filePath = RuoYiConfig.getDownloadPath() + fileName;
+
+            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
+            FileUtils.setAttachmentResponseHeader(response, realFileName);
+            FileUtils.writeBytes(filePath, response.getOutputStream());
+            if (delete) {
+                FileUtils.deleteFile(filePath);
+            }
+        } catch (Exception e) {
+            log.error("下载文件失败", e);
+        }
+    }
+
+    /**
+     * 通用上传请求(单个)
+     */
+    @PostMapping("/upload")
+    public AjaxResult uploadFile(MultipartFile file) throws Exception {
+        try {
+            // 上传文件路径
+            String filePath = RuoYiConfig.getUploadPath();
+            // 上传并返回新文件名称
+            String fileName = FileUploadUtils.upload(filePath, file);
+            String url = serverConfig.getUrl() + fileName;
+            AjaxResult ajax = success();
+            ajax.put("url", url);
+            ajax.put("fileName", fileName);
+            ajax.put("newFileName", FileUtils.getName(fileName));
+            ajax.put("originalFilename", file.getOriginalFilename());
+            return ajax;
+        } catch (Exception e) {
+            return AjaxResult.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 通用上传请求(多个)
+     */
+    @PostMapping("/uploads")
+    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
+        try {
+            // 上传文件路径
+            String filePath = RuoYiConfig.getUploadPath();
+            List<String> urls = new ArrayList<String>();
+            List<String> fileNames = new ArrayList<String>();
+            List<String> newFileNames = new ArrayList<String>();
+            List<String> originalFilenames = new ArrayList<String>();
+            for (MultipartFile file : files) {
+                // 上传并返回新文件名称
+                String fileName = FileUploadUtils.upload(filePath, file);
+                String url = serverConfig.getUrl() + fileName;
+                urls.add(url);
+                fileNames.add(fileName);
+                newFileNames.add(FileUtils.getName(fileName));
+                originalFilenames.add(file.getOriginalFilename());
+            }
+            AjaxResult ajax = success();
+            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
+            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
+            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
+            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
+            return ajax;
+        } catch (Exception e) {
+            return AjaxResult.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 本地资源通用下载
+     */
+    @GetMapping("/download/resource")
+    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
+            throws Exception {
+        try {
+            if (!FileUtils.checkAllowDownload(resource)) {
+                throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
+            }
+            // 本地资源路径
+            String localPath = RuoYiConfig.getProfile();
+            // 数据库资源地址
+            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
+            // 下载名称
+            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
+            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
+            FileUtils.setAttachmentResponseHeader(response, downloadName);
+            FileUtils.writeBytes(downloadPath, response.getOutputStream());
+        } catch (Exception e) {
+            log.error("下载文件失败", e);
+        }
+    }
+
+    /**
+     * 导入execl数据(单个文件)
+     */
+
+    @Anonymous
+    @ApiOperation("上传文件")
+    @PostMapping(value = "/uploadData", headers = "content-type=multipart/form-data")
+    public AjaxResult uploadDataFile(@RequestPart("file") MultipartFile file) throws Exception {
+        Map<String, Object> map = new HashMap<>();
+
+        System.out.println(file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(".")));
+
+        map.put("tableName", file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(".")));
+        map.put("databaseType", SecurityUtils.getDatabaseType());
+        map.put("databaseName", SecurityUtils.getDatabaseName());
+        try {
+            // 创建一个工作簿对象 解析上传的excel表数据
+            List<Map<String, String>> listMap = convertList(EasyExcel.read(file.getInputStream()).sheet().headRowNumber(0).doReadSync());
+            // 查询当前文件插入表结构
+            List<TableInfo> tableInfoList = dataSourceService.tableFieldInfo(map);
+            Map<String, Object> fieldMap = new HashMap<>(); // 存储 字段描述:字段列名
+            tableInfoList.forEach(item -> {
+                fieldMap.put(item.getFieldDescription(), item.getFieldName());
+            });
+            listMap.get(0).forEach((mKey, mVal) -> {
+                if (mVal != null) listMap.get(0).put(mKey, fieldMap.get(mVal).toString());
+            });
+            // 挣个excel文件数据
+            listMap.forEach(item -> {
+                if (listMap.indexOf(item) == 0) return;
+                Map<String, String> handleMap = new HashMap<>(item);
+                handleMap.forEach((mKey, mVal) -> {
+                    // 新增       // 删除当前map中的k/v
+                    item.put(listMap.get(0).get(mKey), item.remove(mKey));
+                });
+                System.out.println(listMap);
+                System.out.println("-----------------");
+            });
+            listMap.remove(0);
+            Map<String, Object> endMap = new HashMap<>();
+            endMap.put("tableName", "test");
+            endMap.put("field", listMap);
+            commonService.batchInsert(endMap);
+            for (Map<String, String> data : listMap) {
+                log.info(JSON.toJSONString(data));
+            }
+        } catch (Exception e) {
+            return AjaxResult.error(e.getMessage());
+        }
+        return null;
+    }
+
+
+    public static List<Map<String, String>> convertList(List<Map<Integer, String>> inputList) {
+        List<Map<String, String>> resultList = new ArrayList<>();
+        for (Map<Integer, String> inputMap : inputList) {
+            Map<String, String> resultMap = new HashMap<>();
+            for (Map.Entry<Integer, String> entry : inputMap.entrySet()) {
+                Integer key = entry.getKey();
+                String value = entry.getValue();
+                // 将 Integer 类型的 key 转换为 String 类型
+                String convertedKey = key.toString();
+                resultMap.put(convertedKey, value);
+            }
+            resultList.add(resultMap);
+        }
+        return resultList;
+    }
+}

+ 1 - 1
ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java

@@ -35,7 +35,7 @@ public class SwaggerConfig
     private boolean enabled;
 
     /** 设置请求的统一前缀 */
-    @Value("${swagger.pathMapping}")
+    @Value("")
     private String pathMapping;
 
     /**

+ 21 - 2
ruoyi-common/pom.xml

@@ -52,13 +52,13 @@
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
         </dependency>
-  
+
         <!-- JSON工具类 -->
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
         </dependency>
-        
+
         <!-- 动态数据源 -->
 		<dependency>
 			<groupId>com.baomidou</groupId>
@@ -89,7 +89,26 @@
             <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml</artifactId>
         </dependency>
+        <!-- excel工具 -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel</artifactId>
+            <version>3.1.0</version>
+            <exclusions>
+                <exclusion>
+                    <artifactId>poi-ooxml-schemas</artifactId>
+                    <groupId>org.apache.poi</groupId>
+                </exclusion>
+            </exclusions>
+        </dependency>
 
+        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.18.22</version>
+            <scope>provided</scope>
+        </dependency>
         <!-- yml解析器 -->
         <dependency>
             <groupId>org.yaml</groupId>

+ 34 - 47
ruoyi-common/src/main/java/com/ruoyi/common/utils/SecurityUtils.java

@@ -9,22 +9,17 @@ import com.ruoyi.common.exception.ServiceException;
 
 /**
  * 安全服务工具类
- * 
+ *
  * @author ruoyi
  */
-public class SecurityUtils
-{
+public class SecurityUtils {
     /**
      * 用户ID
      **/
-    public static Long getUserId()
-    {
-        try
-        {
+    public static Long getUserId() {
+        try {
             return getLoginUser().getUserId();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -32,29 +27,21 @@ public class SecurityUtils
     /**
      * 获取部门ID
      **/
-    public static Long getDeptId()
-    {
-        try
-        {
+    public static Long getDeptId() {
+        try {
             return getLoginUser().getDeptId();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
         }
     }
-    
+
     /**
      * 获取用户账户
      **/
-    public static String getUsername()
-    {
-        try
-        {
+    public static String getUsername() {
+        try {
             return getLoginUser().getUsername();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -63,27 +50,31 @@ public class SecurityUtils
      * 获取数据源类型
      */
     public static String getDatabaseType() {
-        try
-        {
+        try {
             return getLoginUser().getUser().getTenant().getDataSource().getDatabaseType();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取获取数据源类型异常", HttpStatus.UNAUTHORIZED);
         }
     }
 
+    /**
+     * 获取数据源名称
+     */
+    public static String getDatabaseName() {
+        try {
+            return getLoginUser().getUser().getTenant().getDataSource().getDatabaseName();
+        } catch (Exception e) {
+            throw new ServiceException("获取获取数据名称异常", HttpStatus.UNAUTHORIZED);
+        }
+    }
+
     /**
      * 获取用户
      **/
-    public static LoginUser getLoginUser()
-    {
-        try
-        {
+    public static LoginUser getLoginUser() {
+        try {
             return (LoginUser) getAuthentication().getPrincipal();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
         }
     }
@@ -91,8 +82,7 @@ public class SecurityUtils
     /**
      * 获取Authentication
      */
-    public static Authentication getAuthentication()
-    {
+    public static Authentication getAuthentication() {
         return SecurityContextHolder.getContext().getAuthentication();
     }
 
@@ -102,8 +92,7 @@ public class SecurityUtils
      * @param password 密码
      * @return 加密字符串
      */
-    public static String encryptPassword(String password)
-    {
+    public static String encryptPassword(String password) {
         BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         return passwordEncoder.encode(password);
     }
@@ -111,24 +100,22 @@ public class SecurityUtils
     /**
      * 判断密码是否相同
      *
-     * @param rawPassword 真实密码
+     * @param rawPassword     真实密码
      * @param encodedPassword 加密后字符
      * @return 结果
      */
-    public static boolean matchesPassword(String rawPassword, String encodedPassword)
-    {
+    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
         BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         return passwordEncoder.matches(rawPassword, encodedPassword);
     }
 
     /**
      * 是否为管理员
-     * 
+     *
      * @param userId 用户ID
      * @return 结果
      */
-    public static boolean isAdmin(Long userId)
-    {
+    public static boolean isAdmin(Long userId) {
         return userId != null && 1L == userId;
     }
 }

+ 33 - 4
ruoyi-system/src/main/java/com/ruoyi/system/entity/CommonEntity.java

@@ -1,6 +1,7 @@
 package com.ruoyi.system.entity;
 
 import com.ruoyi.common.core.domain.BaseEntity;
+import org.springframework.web.multipart.MultipartFile;
 
 import java.util.Map;
 import java.util.TreeMap;
@@ -27,6 +28,14 @@ public class CommonEntity extends BaseEntity {
      */
     private Map<String, Object> retMap;
 
+    /**
+     * 导入数据Map
+     */
+    private Map<String, Object> execlMap;
+
+
+    private MultipartFile file;
+
     public CommonEntity() {
     }
 
@@ -36,9 +45,19 @@ public class CommonEntity extends BaseEntity {
                 "formMap=" + formMap +
                 ", condition=" + condition +
                 ", retMap=" + retMap +
+                ", execlMap=" + execlMap +
+                ", file=" + file +
                 '}';
     }
 
+    public CommonEntity(Map<String, Object> formMap, Map<String, Object> condition, Map<String, Object> retMap, Map<String, Object> execlMap, MultipartFile file) {
+        this.formMap = formMap;
+        this.condition = condition;
+        this.retMap = retMap;
+        this.execlMap = execlMap;
+        this.file = file;
+    }
+
     public Map<String, Object> getFormMap() {
         return formMap;
     }
@@ -63,9 +82,19 @@ public class CommonEntity extends BaseEntity {
         this.retMap = retMap;
     }
 
-    public CommonEntity(Map<String, Object> formMap, Map<String, Object> condition, Map<String, Object> retMap) {
-        this.formMap = formMap;
-        this.condition = condition;
-        this.retMap = retMap;
+    public Map<String, Object> getExeclMap() {
+        return execlMap;
+    }
+
+    public void setExeclMap(Map<String, Object> execlMap) {
+        this.execlMap = execlMap;
+    }
+
+    public MultipartFile getFile() {
+        return file;
+    }
+
+    public void setFile(MultipartFile file) {
+        this.file = file;
     }
 }

+ 1 - 2
ruoyi-system/src/main/java/com/ruoyi/system/mapper/CommonMapper.java

@@ -30,11 +30,10 @@ public interface CommonMapper {
      * 修改
      */
     int edit(@Param("fields") Map<String, Object> fields, @Param("tableName") String tableName, @Param("conditions") Map<String, Object> conditions);
-
     /**
      * 执行动态sql
      *
-     * @param Sql
+     * @param Sql     执行的sql
      * @return
      */
     List<CommonEntity> queryTableList(String Sql);

+ 4 - 0
ruoyi-system/src/main/java/com/ruoyi/system/service/ICommonService.java

@@ -39,5 +39,9 @@ public interface ICommonService {
      * 导出列表
      */
     void export(HttpServletResponse response,String tableName,String sqlKey) throws Exception;
+    /**
+     * 导出模版
+     */
+    void exportTemplate(HttpServletResponse response,String tableName,String sqlKey) throws Exception;
 
 }

+ 34 - 9
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/CommonServiceImpl.java

@@ -3,6 +3,7 @@ package com.ruoyi.system.service.impl;
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSONObject;
 import com.ruoyi.common.core.domain.model.LoginUser;
+import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.system.entity.CommonEntity;
 import com.ruoyi.system.entity.TableSql;
@@ -45,7 +46,8 @@ public class CommonServiceImpl implements ICommonService {
         List<Object> list = (List<Object>) map.get("field");
         List<Map<String, Object>> mapList = new ArrayList<>();
         for (Object obj : list) {
-            Map<String, Object> map1 = JSONObject.parseObject(JSON.toJSONString(obj));
+            System.out.println(obj);
+            Map<String, Object> map1 = (Map<String, Object>) obj;
             mapList.add(map1);
         }
         Set<String> fieldNames = new LinkedHashSet<>();
@@ -113,13 +115,13 @@ public class CommonServiceImpl implements ICommonService {
         Map<String, String> map = (Map) JSONObject.parseObject(tableSql.getTableExportField());
         // 创建Excel文档
         XSSFWorkbook workbook = new XSSFWorkbook();
-        XSSFSheet sheet = workbook.createSheet("Sheet1");
+        XSSFSheet sheet = workbook.createSheet("Sheet10");
 
         List<String> titleList = new ArrayList<>();
         List<String> fieldList = new ArrayList<>();
         for (Map.Entry<String, String> entry : map.entrySet()) {
             fieldList.add(entry.getKey());
-            titleList.add(entry.getValue());
+            titleList.add(entry.getValue() == null ? "" : entry.getValue());
         }
         // 创建表头
         XSSFRow header = sheet.createRow(0);
@@ -131,22 +133,45 @@ public class CommonServiceImpl implements ICommonService {
         for (int w = 0; w < commonEntities.size(); w++) {
             XSSFRow row = sheet.createRow(rowIndex++);
             for (int e = 0; e < fieldList.size(); e++) {
-                String val = commonEntities.get(w).getRetMap().get(toUnderScoreCase(fieldList.get(e))).toString();
-                row.createCell(e).setCellValue(val);
+                Object val = commonEntities.get(w).getRetMap().get(toUnderScoreCase(fieldList.get(e)));
+                row.createCell(e).setCellValue((val == null ? "" : val).toString());
             }
-
         }
         response.setContentType("application/vnd.ms-excel");
-        response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");
-
+        response.setHeader("Content-Disposition", "attachment; filename=" + DateUtils.dateTimeNow() + ".xlsx");
         // 将Excel文档写入响应流中
         ServletOutputStream outputStream = response.getOutputStream();
         workbook.write(outputStream);
         outputStream.flush();
         outputStream.close();
-
     }
 
+    @Override
+    public void exportTemplate(HttpServletResponse response, String tableName, String sqlKey) throws Exception {
+        //查询标题信息
+        TableSql tableSql = tableSqlMapper.selectTableSqlByTSqlKey(sqlKey);
+        //获取列表标题和字段
+        Map<String, String> map = (Map) JSONObject.parseObject(tableSql.getTableExportField());
+        // 创建Excel文档
+        XSSFWorkbook workbook = new XSSFWorkbook();
+        XSSFSheet sheet = workbook.createSheet("Sheet1");
+        List<String> titleList = new ArrayList<>();
+        for (Map.Entry<String, String> entry : map.entrySet()) {
+            titleList.add(entry.getValue() == null ? "" : entry.getValue());
+        }
+        // 创建表头
+        XSSFRow header = sheet.createRow(0);
+        for (int q = 0; q < titleList.size(); q++) {
+            header.createCell(q).setCellValue(titleList.get(q));
+        }
+        response.setContentType("application/vnd.ms-excel");
+        response.setHeader("Content-Disposition", "attachment; filename=" + DateUtils.dateTimeNow() + ".xlsx");
+        // 将Excel文档写入响应流中
+        ServletOutputStream outputStream = response.getOutputStream();
+        workbook.write(outputStream);
+        outputStream.flush();
+        outputStream.close();
+    }
 
     public static String extractSubstring(String input, String identifier) {
         int startIndex = input.indexOf(identifier);

+ 2 - 4
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/DataSourceServiceImpl.java

@@ -56,7 +56,7 @@ public class DataSourceServiceImpl implements IDataSourceService {
             genConfig.setUrl("jdbc:sqlserver://" + dataSource.getDatabaseIp() + ":" + dataSource.getPortNumber() + ";DatabaseName=" + dataSource.getDatabaseName());
         } else if (dataSource.getDatabaseType().equals(DataSourceType.ORACLE.getDataSourceName())) {
             genConfig.setDriverClassName("oracle.jdbc.driver.OracleDriver");
-            genConfig.setUrl("jdbc:oracle:thin:@" + dataSource.getDatabaseIp() + ":" + dataSource.getPortNumber()+":" + dataSource.getDatabaseName());
+            genConfig.setUrl("jdbc:oracle:thin:@" + dataSource.getDatabaseIp() + ":" + dataSource.getPortNumber() + ":" + dataSource.getDatabaseName());
         } else if (dataSource.getDatabaseType().equals(DataSourceType.DM.getDataSourceName())) {
             genConfig.setDriverClassName("dm.jdbc.driver.DmDriver");
             genConfig.setUrl("jdbc:dm://" + dataSource.getDatabaseIp() + ":" + dataSource.getPortNumber() + "?schema=" + dataSource.getDatabaseName());
@@ -111,8 +111,6 @@ public class DataSourceServiceImpl implements IDataSourceService {
     @Override
     public List<TableInfo> tableFieldInfo(Map<String, Object> map) {
         DataSource dataSource = JSON.parseObject(JSON.toJSONString(map), DataSource.class);
-        String dataBaseName = dataSource.getDatabaseName();
-        // JSON.parseObject(redisTemplate.opsForValue().get("DataSource").toString(), DataSource.class);
         if (dataSource.getDatabaseType().equals(DataSourceType.MYSQL.getDataSourceName())) {
             return tableInfoMapper.mysqlTableFieldInfo(dataSource.getDatabaseName(), map.get("tableName").toString());
         } else if (dataSource.getDatabaseType().equals(DataSourceType.SQLSERVER.getDataSourceName())) {
@@ -120,7 +118,7 @@ public class DataSourceServiceImpl implements IDataSourceService {
         } else if (dataSource.getDatabaseType().equals(DataSourceType.DM.getDataSourceName())) {
             return tableInfoMapper.dmTableFieldInfo(dataSource.getDatabaseName(), map.get("tableName").toString());
         }
-        return tableInfoMapper.mysqlTableFieldInfo(dataBaseName, map.get("tableName").toString());
+        return tableInfoMapper.mysqlTableFieldInfo(dataSource.getDatabaseName(), map.get("tableName").toString());
     }