com.github.xiaoyuge5201.util.ExportDatabaseDocument Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of datasource-spring-boot-starter Show documentation
Show all versions of datasource-spring-boot-starter Show documentation
数据库连接工具,查询mysql、oracle、sqlserver、postgresql的数据表以及字段信息;同时支持导出数据库设计文档
package com.github.xiaoyuge5201.util;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.github.xiaoyuge5201.entity.ColumnEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 导出设计文档
*
* @author yugb
*/
public class ExportDatabaseDocument {
/**
* 导出设计文档
* @param response 返回
* @param request 请求
* @param driverClassName 驱动
* @param url 地址
* @param username 用户
* @param password 密码
* @param database 数据库
*/
public static void export(HttpServletResponse response, HttpServletRequest request, String driverClassName, String url, String username, String password, String database) {
try {
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setContentType("application/x-msdownload;");
String filename = "数据库设计文档" + LocalDateTime.now() + ".xlsx" ;
response.setHeader("Content-disposition", "attachment; filename="
+ new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
XSSFWorkbook result = new XSSFWorkbook();
List list = QuerySqlUtil.listColumnsByDatasourceParams(driverClassName, url, username, password, database);
assert list != null;
list.stream().collect(Collectors.groupingBy(ColumnEntity::getTableName)).forEach((tableName, tableDescs) -> {
TemplateExportParams params = new TemplateExportParams("template-tableDesc.xlsx");//WEB-INF/classes/
Map map = new HashMap<>(16);
map.put("maplist", tableDescs);
map.put("TABLE_NAME", tableName);
String tem = (tableDescs.get(0).getTableComment() == null) ? "" : tableDescs.get(0).getTableComment();
map.put("TABLE_COMMENT", tem);
Workbook r = ExcelExportUtil.exportExcel(params, map);
if (r != null) {
WorkbookUtils.copySheet(result, (XSSFSheet) r.getSheetAt(0), (XSSFSheet) result.createSheet(tableName));
}
});
result.write(response.getOutputStream());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}