想必大家在交付項目時,都遇到這種情況,甲方需要數據庫的表結構,但光一個數據庫就有幾十張表,一個一個手寫的話,那肯定會浪費掉很多摸魚的時間,如果使用Navicat導出為Excel的話,你又會發現連同數據一起導出了,這必然是不妥的,那如何優雅而省時的將這幾十張表導出呢?這個時候就應該想到poi,附上代碼:
首先導入依賴:點擊查看代碼
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi</artifactid>
<version>4.1.0</version>
</dependency>
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi-ooxml</artifactid>
<version>4.1.0</version>
</dependency>
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<version>5.1.48</version>
</dependency>
其次開始優雅導出
點擊查看代碼
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.sql.*;
import java.util.*;
public class TabelToExcel {
private String tableName = "";//表名
private String[] colNames; // 列名數組
private String[] colComment; // 列名數組
private String[] colTypes; //列名類型數組
private int[] colSizes; //列名大小數組
//數據庫連接
private static final String URL ="jdbc:mysql://localhost:3306/test?useSSL=false&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8";
private static final String NAME = "root";
private static final String PASS = "Qroot";
private static final String DRIVER ="com.mysql.jdbc.Driver";
public void genEntitySomeTable(List<String> tableNames){
for(int p=0;p<tableNames.size();p++){
tableName=tableNames.get(p);
//創建連接
Connection con = null;
//查要生成實體類的表
String sql = "select * from " + tableName;
String sql2 = "show full fields from " + tableName;
PreparedStatement pStemt = null;
PreparedStatement pStemt2 = null;
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
con = DriverManager.getConnection(URL,NAME,PASS);
pStemt = con.prepareStatement(sql);
ResultSetMetaData rsmd = pStemt.getMetaData();
pStemt2 = con.prepareStatement(sql2);
ResultSet rsResultSet=pStemt2.executeQuery();
int size = rsmd.getColumnCount(); //統計列
colNames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
colComment = new String[size];
int j=0;
while (rsResultSet.next()) {
//System.out.println(rsResultSet.getObject(9));
colComment[j]=rsResultSet.getObject(9).toString();
j++;
}
for (int i = 0; i < size; i++) {
colNames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if (colTypes[i] .equals("INT")){
colTypes[i] = "INTEGER";
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
createExcel();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if (con != null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println("生成完畢!");
}
public void createExcel() throws Exception{
//獲取Excel模版文件目錄
String path = "C:\\Users\\Desktop\\test.xlsx";
path = path.replaceAll("%20", " ");
try(InputStream fileInputStream = new FileInputStream(path);
//通過Excel模板目錄獲取Excel模版文件
XSSFWorkbook workbook1 = new XSSFWorkbook(OPCPackage.open(fileInputStream));
//利用POI3.8及其以上,每個Sheet可以存1,048,576行數據,每行可以有16,384列數據
Workbook workbook = new SXSSFWorkbook(workbook1, 100)){
//重命名sheet工作表名稱:第幾個工作表
workbook.setSheetName(0, tableName);
//創建sheet工作表
SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
//從模板sheet工作表第幾行開始插入(注意行、列、單元格都是從0開始數)
int startRow =1;
for (int i = 0;i<colSizes.length;i++){
Row row = sheet.createRow(startRow++);
row.createCell(1).setCellValue(colNames[i]);
row.createCell(2).setCellValue(colTypes[i] + "(" + colSizes[i] + ")");
row.createCell(3).setCellValue(colComment[i]);
}
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
workbook.write(outputStream);
//輸出目錄
String filePath = "C:\\Users\\Desktop\\" + tableName + ".xlsx";
File file = new File(filePath);
try(FileOutputStream fileOutputStream = new FileOutputStream(file);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray())) {
byte[] bytes = new byte[1024];
int len;
while ((len = byteArrayInputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,len);
}
}
}
}
}
public static void main(String[] args) {
TabelToExcel tableToExcel = new TabelToExcel();
List<String> dataList = new ArrayList<>();
//添加表名
dataList.add("test");
tableToExcel.genEntitySomeTable(dataList);
}
}
整個邏輯還是很好理解的,但是這里需要注意修改自己excel模板的路徑,導出路徑,以及數據庫的連接路徑。好了,到此,只需要你輸入表名稱,就可以將表結構導出為excel了!
excel模板:
導出效果: