想必大家在交付项目时,都遇到这种情况,甲方需要数据库的表结构,但光一个数据库就有几十张表,一个一个手写的话,那肯定会浪费掉很多摸鱼的时间,如果使用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模板:
导出效果: