當我們在編輯Word文檔時,如果遇到大量資料需要展現,可以選擇直接在Word文檔中建立表格。将資料應用于表格内,不僅能夠簡化文檔語言,而且也可以使資料内容更加清晰、直覺。下面我就将使用Free Spire.Doc
for Java示範如何在Java中建立Word表格。
安裝Spire.Doc.Jar
方法一:
如果您使用的是 maven,可以通過添加以下代碼到項目的 pom.xml 檔案中,将 JAR 檔案導入到應用程式中。
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
方法二:
在Word中建立表格:
具體操作步驟:
- 建立一個Document對象,并向其添加一個節。
- 将标題行和其他行的資料分别存儲在一維字元串數組和二維字元串數組中。
- 使用Section.addTable()方法将表格添加到節。
- 将資料插入标題行,并設定行格式,包括行高、背景顔色和文本對齊方式。
- 将資料插入其餘行,并對這些行應用格式。
- 使用Document.saveToFile()方法儲存檔案。
相關代碼:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class CreateTable
{
public static void main(String[] args)
{
//建立一個Document對象
Document document = new Document();
//添加一個節
Section section = document.addSection();
//定義表格資料
String[] header = { "學号", "姓名", "性别", "班級", "成績" };
String[][] data =
{
new String[]{"0105", "李雷", "男", "1", "88"},
new String[]{"0721", "趙文", "女", "7", "92"},
new String[]{"1131", "陳華", "女", "11", "91"},
new String[]{"0418", "宋野", "男", "4", "95"},
new String[]{"0513", "韓梅", "女", "5", "94"},
};
//添加表格
Table table = section.addTable(true);
table.resetCells(data.length + 1, header.length);
//将第一行設定為表格标題
TableRow row = table.getRows().get(0);
row.isHeader(true);
row.setHeight(20);
row.setHeightType(TableRowHeightType.Exactly);
row.getRowFormat().setBackColor(Color.gray);
for (int i = 0; i < header.length; i++)
{
row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
Paragraph p = row.getCells().get(i).addParagraph();
p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
TextRange txtRange = p.appendText(header[i]);
txtRange.getCharacterFormat().setBold(true);
}
//将資料添加到其餘行
for (int r = 0; r < data.length; r++)
{
TableRow dataRow = table.getRows().get(r + 1);
dataRow.setHeight(25);
dataRow.setHeightType(TableRowHeightType.Exactly);
dataRow.getRowFormat().setBackColor(Color.white);
for (int c = 0; c < data[r].length; c++)
{
dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
}
}
//設定單元格的背景顔色
for (int j = 1; j < table.getRows().getCount(); j++)
{
if (j % 2 == 0)
{
TableRow row2 = table.getRows().get(j);
for (int f = 0; f < row2.getCells().getCount(); f++)
{
row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
}
}
}
//儲存結果檔案
document.saveToFile("result.docx", FileFormat.Docx_2013);
}
}