A table in Microsoft Word is a useful tool for presenting data. It allows you to arrange large amounts of data using a grid of rows and columns so that readers can read and analyze them more easily. In this article, I will demonstrate how to create or read tables in Word documents in Java using Free Spire.Doc for Java library.
Add Dependencies
Before coding, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that.
Method 1: If you are using maven, you can easily import the JAR file of Free Spire.Doc for Java into your application by adding the following code to your project’s pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
Method 2: If you are not using maven, you can download Free Spire.Doc for Java from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.
Create a Table in a Word Document in Java
Free Spire.Doc for Java provides the Section.addTable() method to add a table to a specific section of a Word document. Once the table is added, you can perform various manipulations on it, such as horizontally/vertically merging table cells, adding data, and applying formatting. The detailed steps are as follows:
- Initialize an instance of the Document class and load a Word document using Document.loadFromFile() method.
- Get a specific section by its index using Document.getSections().get(int) method.
- Define the data of the header row and data rows of the table, and store them in a one-dimensional string array and a two-dimensional string array respectively.
- Add a table to the section using Section.addTable() method.
- Specify the number of rows and columns of the table according to the length of the data using Table.resetCells() method.
- Horizontally merge specific cells in the table using Table.applyHorizontalMerge() method.
- Set data and formatting for the header row of the table.
- Set data and formatting for the data rows of the table.
- Set background color for specific rows of the table.
- Save the result document using Document.saveToFile() method.
import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TableRowHeightType;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class CreateTable {
public static void main(String []args) {
//Initialize an instance of the Document class
Document document = new Document();
//Load a Word document
document.loadFromFile("Sample.docx");
//Get the first section
Section section = document.getSections().get(0);
//Define table data
String[] header = {"Name", "Department", "Salary"};
String[][] data =
{
new String[]{"Kline", "Computer Science", "$10,000,000"},
new String[]{"Martin", "Arts & Craft", "$2,000,000"},
new String[]{"Mendes", "Research & Dev.", "$3,800,000"},
new String[]{"Patrick", "Computer Science", "$28,000,000"},
new String[]{"Total", "", "$43,800,000"},
};
//Add a table to the section
Table table = section.addTable(true);
//Specify the number of rows and columns of the table
table.resetCells(data.length + 1, header.length);
//Horizontally merge specific cells
table.applyHorizontalMerge(5, 0, 1);
//Set data and format for the header row of the table
TableRow row = table.getRows().get(0);
row.isHeader(true);
row.setHeight(30);
row.setHeightType(TableRowHeightType.Exactly);
row.getRowFormat().setBackColor(new Color(142, 170, 219));
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().setFontSize(14);
txtRange.getCharacterFormat().setBold(true);
txtRange.getCharacterFormat().setTextColor(Color.white);
}
//Set data and format for the data rows of the table
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]);
}
}
//Set background color for specific table rows
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(217, 226, 243));
}
}
}
//Save the result document
document.saveToFile("CreateTable.docx", FileFormat.Docx);
}
}
Read a Table in a Word Document in Java
To read the data in a table, you need to iterate through all rows in the table, all cells in each row, and all paragraphs in each cell, then extract the data from each paragraph and save them into a text file. The detailed steps are as follows:
- Initialize an instance of the Document class.
- Load a Word document using Document.loadFromFile() method.
- Get a specific section by its index using Document.getSections().get(int) method.
- Get a specific table in the section by its index using Section.getTables().get(int) method.
- Initialize an instance of the StringBuilder class.
- Iterate through all rows in the table.
- Iterate through all cells in each row.
- Iterate through all paragraphs in each cell.
- Get the text from each paragraph using Paragraph.getText() method and save the result into the StringBuilder.
- Write the text in the StringBuilder into a text file.
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.TableCell;
import com.spire.doc.TableRow;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.interfaces.ITable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ReadTableData {
public static void main(String []args) throws IOException {
//Initialize an instance of the Document class
Document document = new Document();
//Load a Word document
document.loadFromFile("CreateTable.docx");
//Get the first section
Section section = document.getSections().get(0);
//Get the first table in the first section
ITable table = section.getTables().get(0);
//Initialize an instance of the StringBuilder class
StringBuilder sb = new StringBuilder();
//Iterate through all rows in the table
for (int i = 0; i < table.getRows().getCount(); i++) {
TableRow row = table.getRows().get(i);
//Iterate through all cells in each row
for (int j = 0; j < row.getCells().getCount(); j++) {
TableCell cell = row.getCells().get(j);
//Iterate through all paragraphs in each cell
for (int k = 0; k < cell.getParagraphs().getCount(); k++) {
//Extract text from each paragraph
Paragraph paragraph = cell.getParagraphs().get(k);
String text = paragraph.getText();
//Append the text to the StringBuilder
sb.append(text+ " ");
}
}
sb.append("\r\n");
}
//Save the text in the StringBuilder to a txt file
File file = new File("TableData.txt");
if (file.exists())
{
file.delete();
}
FileWriter fWriter = new FileWriter("TableData.txt", true);
try {
fWriter.write(sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fWriter.flush();
fWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Top comments (0)