領導將數據字典中生成word文檔的功能交給了一位同事,他過來和我討論。經過一番搜索找到了使用Apache POI這個開源框架的方法,不得不說這個框架真的非常的優秀,下面我將貼出我用來測試的代碼(由於時間比較有限,就沒有細緻得整理代碼),供以後參考使用。
1.pom依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
2.java 代碼
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.TableWidthType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class Test {
public static void main(String[] args) {
// 文檔生成方法
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph(); // 創建段落
XWPFRun r1 = p1.createRun(); // 創建段落文本
r1.setText("目錄"); // 設置文本
FileOutputStream out = null; // 創建輸出流
try {
// 向word文檔中添加內容
XWPFParagraph p3 = doc.createParagraph(); // 創建段落
XWPFRun r3 = p3.createRun(); // 創建段落文本
r3.addTab();// tab
r3.addBreak();// 換行
r3.setBold(true);
XWPFParagraph p2 = doc.createParagraph(); // 創建段落
XWPFRun r2 = p2.createRun(); // 創建段落文本
// 設置文本
r2.setText("表名");
r2.setFontSize(14);
r2.setBold(true);
XWPFTable table1 = doc.createTable(8, 10);
table1.setWidthType(TableWidthType.AUTO);
// 獲取到剛剛插入的行
XWPFTableRow row1 = table1.getRow(0);
// 設置單元格內容
row1.getCell(0).setText("字段名");
row1.getCell(1).setText("字段說明");
row1.getCell(2).setText("數據類型");
row1.getCell(3).setText("長度");
row1.getCell(4).setText("索引");
row1.getCell(5).setText("是否爲空");
row1.getCell(6).setText("主鍵");
row1.getCell(7).setText("外鍵");
row1.getCell(8).setText("缺省值");
row1.getCell(9).setText("備註");
doc.setTable(0, table1);
String filePath = "D:\\simple.docx";
out = new FileOutputStream(new File(filePath));
doc.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}