Java export database table information to generate Word document

I. Preface

Recently, I saw my friend write a business of exporting database to generate word document. It's very interesting. After a study, I'll share it with you~

Let's see the effect of the generated word document first

Let's implement it together

2. Java exports database table information to generate Word document

Warm tip: the following is just a simple display of some major codes. For details, please refer to the case demo source code given at the end of the article.

Basic environment
  1. spring-boot 2.1.8
  2. mybatis-plus 2.2.0
  3. mysql database

1. Add dependency

		<!-- ================== Generate database table information word Required for document information ====================== -->
        <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.lowagie/itext-rtf -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext-rtf</artifactId>
            <version>2.1.7</version>
        </dependency>

2. Query table data information

@Mapper
public interface TableMapper {

    /**
     * Get all table names and comments under the specified database
     *
     * @param dbName:Database name
     * @return: java.util.List<com.zhengqing.demo.modules.system.entity.Tables>
     */
    @Select("select table_name as name,table_comment as comment from information_schema.tables where table_schema =#{dbName} order by table_name")
    List<Tables> getAllTables(@Param("dbName") String dbName);

    /**
     * Get the specified table information
     *
     * @param tableName:surface
     * @return: java.util.List<com.zhengqing.demo.modules.system.entity.TableFileds>
     */
    @Select("SHOW FULL FIELDS FROM ${tableName}")
    List<TableFileds> getTable(@Param("tableName") String tableName);

}

3. Generate word document implementation class

@Service
public class TableService implements ITableService {

    @Autowired
    private TableMapper tableMapper;
    @Autowired
    private TableToWordUtil tableToWordUtil;

    @Override
    public String getTableInfo() {
        // 1. Get all table information of the database
        List<Tables> tables = tableMapper.getAllTables(Constants.DATABASE);

        // 2. Generate file name information - mm / DD / yyyy, HHM / S
        String date = null;
        try {
            date = DateTimeUtils.dateFormat(new Date(), DateTimeUtils.PARSE_PATTERNS[12]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String docFileName = Constants.FILE_PATH + "\\" + Constants.FILE_NAME + "-" + date + ".doc";

        // 3. Call tool class to generate file
        tableToWordUtil.toWord(tables, docFileName, Constants.FILE_NAME);

        // 4. Return file address
        String filePath = docFileName.replaceAll("\\\\", "/");
        return filePath;
    }
}

4. Generate word document tool class

@Service
public class TableToWordUtil {

    @Autowired
    TableMapper tableMapper;

    /**
     * Generate word document
     *
     * @param tables: All table information under this database
     * @param fileName: Build file address
     * @param title:Document content title
     * @return: void
     */
    public void toWord(List<Tables> tables, String fileName, String title) {
        Document document = new Document(PageSize.A4);
        try {
            // create folder
            File dir = new File(Constants.FILE_PATH);
            dir.mkdirs();

            // create a file
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
            file.createNewFile();

            // Write file information
            RtfWriter2.getInstance(document, new FileOutputStream(fileName));
            document.open();
            Paragraph ph = new Paragraph();
            Font f = new Font();
            Paragraph p = new Paragraph(title, new Font(Font.NORMAL, 24, Font.BOLDITALIC, new Color(0, 0, 0)));
            p.setAlignment(1);
            document.add(p);
            ph.setFont(f);
            for (int i = 0; i < tables.size(); i++) {
                String table_name = tables.get(i).getName();
                String table_comment = tables.get(i).getComment();
                List<TableFileds> fileds = tableMapper.getTable(tables.get(i).getName());
                String all = "" + (i + 1) + " Table name:" + table_name + "(" + table_comment + ")";
                Table table = new Table(6);

                document.add(new Paragraph(""));

                table.setBorderWidth(1);
                table.setPadding(0);
                table.setSpacing(0);

                //Add the elements of the header and set the color of the background of the header
                Color chade = new Color(176, 196, 222);

                Cell cell = new Cell("number");
                addCell(table, cell, chade);
                cell = new Cell("Field name");
                addCell(table, cell, chade);
                cell = new Cell("type");
                addCell(table, cell, chade);
                cell = new Cell("Is it not empty?");
                addCell(table, cell, chade);
                cell = new Cell("Is the primary key?");
                addCell(table, cell, chade);
                cell = new Cell("Notes");
                addCell(table, cell, chade);

                table.endHeaders();

                // Body of table
                for (int k = 0; k < fileds.size(); k++) {
                    addContent(table, cell, (k + 1) + "");
                    addContent(table, cell, fileds.get(k).getField());
                    addContent(table, cell, fileds.get(k).getType());
                    addContent(table, cell, fileds.get(k).getNull().equals("YES") ? "no" : "yes");
                    addContent(table, cell, fileds.get(k).getKey() != "" ? "yes" : "no");
                    addContent(table, cell, fileds.get(k).getComment());
                }
                Paragraph pheae = new Paragraph(all);
                //Write table description
                document.add(pheae);
                //Generate tables
                document.add(table);
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Add header to table
     *
     * @param table
     * @param cell
     * @param chade
     */
    private void addCell(Table table, Cell cell, Color chade) {
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(chade);
        table.addCell(cell);
    }

    /**
     * Add content to table
     *
     * @param table
     * @param content
     */
    private void addContent(Table table, Cell cell, String content) {
        cell = new Cell(content);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
    }

}

5. Some constant parameters

public class Constants {

    /**
     * Database for generating word documents
     */
    public static final String DATABASE = "demo";
    /**
     * Build filename prefix
     */
    public static final String FILE_NAME = "Test database";

    /**
     * Build file address
     */
    public static String FILE_PATH = "D:\\www";

}

III. test generation effect

Xiaobian provides a get request interface in demo http://localhost:8080/api/tableToWord

Next, we can go to the returned address to check the generated file

Case demo source code

https://gitee.com/zhengqingya/java-workspace

Tags: Programming Database Java Spring Mybatis

Posted on Fri, 08 Nov 2019 11:02:36 -0800 by alanlee79