java实现根据sql动态下载数据到excel

需求

由于生产数据库不能直接连接下载数据,所以需要在监控系统上做一个根据sql动态查询并下载数据的功能。

实现思路

写一个接口,传入需要查询的数据库信息和sql,将查询的接口导出到Excel中

实现细节

入参

java 复制代码
@Data
public class ExportDataReq {
    /**
     * "jdbc:mysql://localhost:3306/your_database";
     */
    @NotEmpty
    String url;
    @NotEmpty
    String user;
    @NotEmpty
    String password;
    @NotEmpty
    String sql;
    @NotEmpty
    String[] titles;
}

controller

java 复制代码
@Slf4j
@Controller
@RequestMapping("/export/")
public class ExportController {
    @Autowired
    ExportService exportService;

    @ApiOperation(value = "下载数据信息", notes = "日期格式:yyyy-MM-dd", httpMethod = "POST")
    @PostMapping(value = "/exportData")
    @ResponseBody
    public BaseResponse exportData(@RequestBody @Valid ExportDataReq req,HttpServletResponse response) {
        BaseResponse baseResponse = exportService.exportData(req, response);
        return baseResponse;
    }
}

接口

java 复制代码
public interface ExportService {
    BaseResponse exportData(ExportDataReq req, HttpServletResponse response);
}

服务

java 复制代码
@Service
public class ExportServiceImpl implements ExportService {
    @Override
    public BaseResponse exportData(ExportDataReq req, HttpServletResponse response) {
        try (Connection conn = DriverManager.getConnection(req.getUrl(), req.getUser(), req.getPassword());
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(req.getSql())) {
            //创建wb
            HSSFWorkbook wb =  new HSSFWorkbook();
            //创建sheet
            HSSFSheet sheet = wb.createSheet("data");
            //添加标题
            addTitle(sheet,req.getTitles());
            //添加内容
            addRow(sheet,rs);
            //导出
            writeToResponse(response,wb,"data"+dateNow());
            return ResponseUtils.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseUtils.fail(ex.getMessage());
        }finally {

        }

    }
    protected void writeToResponse(HttpServletResponse response, HSSFWorkbook wb, String fileName) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8")+".xls");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.flush();
        wb.close();
    }
    private void addRow(HSSFSheet sheet, ResultSet rs) throws SQLException {
        ResultSetMetaData rsMetaData = rs.getMetaData();
        int columnCount = rsMetaData.getColumnCount();
        int rowNum = 1;
        while (rs.next()) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 1; i <= columnCount; i++) {
                Cell cell = row.createCell(i - 1);
                String columnName = rsMetaData.getColumnName(i);
                switch (rsMetaData.getColumnType(i)) {
                    case Types.VARCHAR:
                    case Types.CHAR:
                        cell.setCellValue(rs.getString(columnName));
                        break;
                    case Types.INTEGER:
                        cell.setCellValue(rs.getInt(columnName));
                        break;
                    case Types.DOUBLE:
                        cell.setCellValue(rs.getDouble(columnName));
                        break;
                    // Add other types as needed
                    default:
                        cell.setCellValue(rs.getString(columnName));
                }
            }
        }
    }

    private void addTitle(HSSFSheet sheet, String[] titles) {
        HSSFRow row = sheet.createRow((int) 0);
        for (int i=0;i<titles.length;i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            sheet.autoSizeColumn(i);//自动设宽
        }
    }
    private String dateNow(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
        return sdf.format(new java.util.Date());
    }
}

然后通过postman即可导出数据,因为入参类型比较复杂,sql可能较长,所以此处使用post请求。

测试

入参

java 复制代码
{"url":"jdbc:mysql://XXXX:63306/gac_order",
"user":"XXX",
"password":"xxx",
"sql":"select order_id,create_time,user_id,status  from order_info limit 1000",
"titles":["order_id","create_time","user_id","status"]}

postman send按钮下拉的Send and Download 可以顺利下载下数据

相关推荐
leegong231114 小时前
PostgreSQL 初中级认证可以一起学吗?
数据库
秋野酱5 小时前
如何在 Spring Boot 中实现自定义属性
java·数据库·spring boot
weisian1516 小时前
Mysql--实战篇--@Transactional失效场景及避免策略(@Transactional实现原理,失效场景,内部调用问题等)
数据库·mysql
AI航海家(Ethan)6 小时前
PostgreSQL数据库的运行机制和架构体系
数据库·postgresql·架构
Kendra9199 小时前
数据库(MySQL)
数据库·mysql
时光书签10 小时前
Mongodb副本集群为什么选择3个节点不选择4个节点
数据库·mongodb·nosql
人才程序员11 小时前
【C++拓展】vs2022使用SQlite3
c语言·开发语言·数据库·c++·qt·ui·sqlite
极客先躯11 小时前
高级java每日一道面试题-2025年01月23日-数据库篇-主键与索引有什么区别 ?
java·数据库·java高级·高级面试题·选择合适的主键·谨慎创建索引·定期评估索引的有效性
指尖下的技术11 小时前
Mysql面试题----MyISAM和InnoDB的区别
数据库·mysql
永远是我的最爱12 小时前
数据库SQLite和SCADA DIAView应用教程
数据库·sqlite