將mysql8.0下指定schema下的表導出爲execl文件

記錄一下,下次需要的時候就可以直接使用啦,方便寫數據庫結構,麼麼噠

注:其它版本的mysql數據庫直接修改驅動類即可

mysql8.0驅動下載地址https://www.cnblogs.com/anovana/articles/8342021.html

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.sql.Connection;

/**
 * 將數據庫表導出爲execl文件
 */
public class TableExeclUtil {
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static String tables = "select table_name,table_comment from information_schema.tables where table_schema = ?";

	private static String tableColumn = "select column_name,column_default,case is_nullable when 'NO' then '可爲空' else '必須' end IS_NULLABLE,column_type,column_comment "
			+ "from information_schema.columns where table_schema = ? and table_name = ?";

	public static void main(String[] args) throws Exception {
		List<String> p = new ArrayList<>();
		p.add("需要導出的schema名字");
		List<Map<String, String>> res = execSql(tables, p);
		// 創建Excel文件對象
		XSSFWorkbook wb = new XSSFWorkbook();
		createExcelTop(wb, "目錄", new String[] { "序號", "表名", "表說明" }, new String[] {"TABLE_NAME", "TABLE_COMMENT"}, res);
		for(int i=0;i<res.size();i++) {
			Map<String, String> onetable = res.get(i);
			p = new ArrayList<>();
			p.add("cimb_batch");
			p.add(onetable.get("TABLE_NAME"));
			List<Map<String, String>> onetablecolumn = execSql(tableColumn, p);
			// for(int j=0;j<onetablecolumn.size();j++) {
				createExcelTop(wb, onetable.get("TABLE_COMMENT").isEmpty() ? onetable.get("TABLE_NAME") : onetable.get("TABLE_COMMENT"),
						new String[] { "序號", "列明名", "默認值", "是否必須", "數據類型", "列說明" },
						new String[] {"COLUMN_NAME", "COLUMN_DEFAULT", "IS_NULLABLE", "COLUMN_TYPE", "COLUMN_COMMENT"},
						onetablecolumn);
			// }
		}
		// 輸出Excel文件
		FileOutputStream output = new FileOutputStream("文件路徑");
		wb.write(output);
		output.flush();
		output.close();
	}

	/**
	 * 執行sql
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	private static List<Map<String, String>> execSql(String sql, List<String> params) {
		List<Map<String, String>> list = new ArrayList<>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = DriverManager.getConnection("連接地址", "用戶名", "密碼");
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setString(i+1, params.get(i));
			}
			rs = ps.executeQuery();
			ResultSetMetaData md = rs.getMetaData(); // 獲得結果集結構信息,元數據
			int columnCount = md.getColumnCount(); // 獲得列數
			while (rs.next()) {
				Map<String, String> rowData = new HashMap<>();
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(md.getColumnName(i), rs.getString(i));
				}
				list.add(rowData);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 創建excel的表頭,設置字體及字體顏色,設置單元格填充色
	 * 
	 * @param hssfWorkbook
	 * @param tableHead
	 * @param data
	 * @throws Exception
	 */
	public static void createExcelTop(XSSFWorkbook xf, String sheetName, String[] tableHead, String[] datacolumn, List<Map<String, String>> data) throws Exception {
		// 創建sheet對象
		Sheet sheet = xf.createSheet(sheetName);
		// 創建row
		Row row = sheet.createRow(1);

		//關鍵點 IndexedColors.AQUA.getIndex() 對應顏色
		CellStyle style = xf.createCellStyle();
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		// 創建cell
		for(int i=0;i<tableHead.length;i++) {
			Cell cell = row.createCell(i+1);
			cell.setCellStyle(style);
			cell.setCellValue(tableHead[i]);
		}

		for (int i = 1; i <= data.size(); i++) {
			Row row2 = sheet.createRow(i+1);
			row2.createCell(1).setCellValue("" + i);
			Map<String, String> onedata = data.get(i-1);
			for(int j=0;j<datacolumn.length;j++) {
				row2.createCell(j+2).setCellValue(onedata.get(datacolumn[j]));
			}
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章