依赖
<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>
</dependency>
主要代码
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class WordExportTable {
public static final String driverUrl = "jdbc:mysql://127.0.0.1:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&allowMultiQueries=true";
public static final String username = "root";
public static final String password = "123456";
public static final String dataBase = "数据库名称";
public static final String notTbales = null;
public static final String notLike = null;
public static final String title = "数据库设计详细说明书";
public static final String path = "C:\\Users\\pc\\Desktop\\";
public static final String fileName = "数据库设计详细说明书V1.0.0.doc";
public static void main(String[] args)throws Exception {
XWPFDocument document= new XWPFDocument();
XWPFParagraph titleParagraph = document.createParagraph();
titleParagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleParagraphRun = titleParagraph.createRun();
titleParagraphRun.setText(title);
titleParagraphRun.setColor("000000");
titleParagraphRun.setFontSize(20);
WordExportTable we = new WordExportTable();
List<JSONObject> list= we.getTables(dataBase);
for (JSONObject json : list) {
List<String[]> columns = we.getTablesDetail(dataBase, json.getString("name"));
addTable(document, json.getString("name"), json.getString("remark"), columns);
}
FileOutputStream out = new FileOutputStream(new File(path+fileName));
document.write(out);
out.close();
System.out.println("create_table document written success.");
}
private List<String[]> getTablesDetail(String schema, String tableName){
List<String[]> list = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(driverUrl, username, password);
String sql = "SELECT COLUMN_NAME , COLUMN_TYPE , COLUMN_DEFAULT , IS_NULLABLE , COLUMN_COMMENT "
+" FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = ? and table_name = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, schema);
preparedStatement.setString(2, tableName);
resultSet = preparedStatement.executeQuery();
int i = 1;
while(resultSet.next()){
String[] str = new String[7];
str[0] = i+"";
str[1] = resultSet.getString("COLUMN_NAME");
str[2] = resultSet.getString("COLUMN_TYPE");
str[3] = resultSet.getString("COLUMN_DEFAULT");
str[4] = resultSet.getString("IS_NULLABLE");
str[5] = "";
str[6] = resultSet.getString("COLUMN_COMMENT");
list.add(str);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
private List<JSONObject> getTables(String schema){
List<JSONObject> list = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(driverUrl, username, password);
StringBuffer sql = new StringBuffer();
sql.append("select TABLE_NAME,TABLE_COMMENT from information_schema.tables where table_schema= ? ");
if(null != notLike){
sql.append(" AND table_name NOT LIKE "+notLike);
}
if(null != notTbales){
sql.append(" AND table_name NOT IN ("+notTbales+")");
}
preparedStatement = connection.prepareStatement(sql.toString());
preparedStatement.setString(1, schema);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
JSONObject j = new JSONObject();
j.put("name", resultSet.getString("TABLE_NAME"));
j.put("remark", resultSet.getString("TABLE_COMMENT"));
list.add(j);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
private static void addTable(XWPFDocument document,String tableName,String remark, List<String[]> columns){
document.createParagraph().createRun().setText("\r");
document.createParagraph().createRun().setText(remark+" "+tableName);
XWPFTable ComTable = document.createTable();
CTTbl ttbl = ComTable.getCTTbl();
int[] COLUMN_WIDTHS = new int[] {572,2072,1372,872,672,672,2572};
CTTblGrid tblGrid = ttbl.getTblGrid() != null ? ttbl.getTblGrid()
: ttbl.addNewTblGrid();
for (int j = 0, len = COLUMN_WIDTHS.length; j < len; j++) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(String.valueOf(COLUMN_WIDTHS[j])));
}
XWPFTableRow comTableRowOne = ComTable.getRow(0);
setCellvalue(comTableRowOne.getCell(0), "序号");
setCellvalue(comTableRowOne.addNewTableCell(),"字段名");
setCellvalue(comTableRowOne.addNewTableCell(),"类型");
setCellvalue(comTableRowOne.addNewTableCell(),"默认值");
setCellvalue(comTableRowOne.addNewTableCell(),"是否可为空");
setCellvalue(comTableRowOne.addNewTableCell(),"是否主键");
setCellvalue(comTableRowOne.addNewTableCell(),"注释");
for (String[] str : columns) {
XWPFTableRow comTableRowTwo = ComTable.createRow();
for (int j = 0; j < str.length; j++) {
if(j==0 || j==3 || j==4 || j==5){
setCellvalue(comTableRowTwo.getCell(j),str[j]);
}else{
comTableRowTwo.getCell(j).setText(str[j]);
}
}
}
}
private static void setCellvalue(XWPFTableCell cell, String text){
cell.setText(text);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
CTTc cttc = cell.getCTTc();
CTP ctp = cttc.getPList().get(0);
CTPPr ctppr = ctp.getPPr();
if (ctppr == null) {
ctppr = ctp.addNewPPr();
}
CTJc ctjc = ctppr.getJc();
if (ctjc == null) {
ctjc = ctppr.addNewJc();
}
ctjc.setVal(STJc.CENTER);
}
}
参考原文地址