Table (9)
Adjusting the column widths in a Word table is crucial for making the document look neat and easy to read. Particularly in tables with a lot of text, appropriate column widths can facilitate smoother reading. Word offers two approaches: percentage-based and fixed widths. Setting column widths by percentage can adapt to various screen sizes, keeping content neatly formatted and more pleasant to read. Using fixed widths stabilizes the table structure, precisely aligning each section, which is especially suitable for tables requiring strict alignment of numbers or complex designs. This article will introduce how to set Word table column widths based on percentage or fixed values using Spire.Doc for Java in Java projects.
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Set Column Width Based on Percentage in Java
To set column widths in a Word table using percentage values, you first need to define the table's width type as percentage. This can be achieved with Table.SetPreferredWidth(new PreferredWidth(WidthType.Percentage, (short)100)). Then, iterate through each column and set their widths to either the same or different percentage values. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.loadFromFile() method.
- Retrieve the first section of the document using Document.getSections().get(0).
- Get the first table within the section using Section.getTables().get(0).
- Use a for loop to iterate through all rows in the table.
- Set the column width for cells in different columns to percentage values using the TableRow.getCells().get(index).setCellWidth(value, CellWidthType.Percentage) method, where value is the percentage width you wish to apply.
- Save the changes to the Word document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; public class PercentageColumnWidth { public static void main(String[] args) { // Create a new Document object Document doc = new Document(); // Load the document doc.loadFromFile("Sample.docx"); // Get the first Section of the document Section section = doc.getSections().get(0); // Cast the first Table in the Section to a Table type Table table = section.getTables().get(0); // Create a PreferredWidth object, set the width type to Percentage, and set the width value to 100% PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short) 100); // Set the Table's preferred width to the PreferredWidth object created above table.setPreferredWidth(percentageWidth); // Define a variable of type TableRow TableRow tableRow; // Iterate over all rows in the Table for (int i = 0; i < table.getRows().getCount(); i++) { // Get the current row tableRow = table.getRows().get(i); // Set the width of the first cell to 34%, type as Percentage tableRow.getCells().get(0).setCellWidth(34, CellWidthType.Percentage); // Set the width of the second cell to 33%, type as Percentage tableRow.getCells().get(1).setCellWidth(33, CellWidthType.Percentage); // Set the width of the third cell to 33%, type as Percentage tableRow.getCells().get(2).setCellWidth(33, CellWidthType.Percentage); } // Save the modified document, specifying the file format as Docx2016 doc.saveToFile("SetColumnWidthsWithPercentageValues.docx", FileFormat.Docx_2016); // Close the document doc.close(); } }
Set Column Width Based on Fixed Value in Java
When setting column widths in a Word table using fixed values, you first need to set the table to a fixed layout. This is done with Table.getTableFormat().setLayoutType(LayoutType.Fixed), then iterate through each column and set the width to the same or different fixed values as required. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.loadFromFile() method.
- Retrieve the first section of the document using Document.getSections().get(0).
- Get the first table within the section using Section.getTables().get(0).
- Use a for loop to iterate through all rows in the table.
- Set the column width for cells in different columns to fixed values using the TableRow.getCells().get(index).setCellWidth(value, CellWidthType.Point) method.
- Save the changes to the Word document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; public class FixedColumnWidth { public static void main(String[] args) { // Create a new Document object Document doc = new Document(); // Load the document doc.loadFromFile("Sample.docx"); // Get the first Section of the document Section section = doc.getSections().get(0); // Cast the first Table in the Section to a Table type Table table = section.getTables().get(0); // Set the table layout type to Fixed table.getTableFormat().setLayoutType(LayoutType.Fixed); // Set the table resizing method to not Auto table.getTableFormat().isAutoResized(false); // Get the left margin float leftMargin = section.getPageSetup().getMargins().getLeft(); // Get the right margin float rightMargin = section.getPageSetup().getMargins().getRight(); // Calculate the page width minus left and right margins double pageWidth = section.getPageSetup().getPageSize().getWidth() - leftMargin - rightMargin; // Define a variable of type TableRow TableRow tableRow; // Iterate through all rows in the Table for (int i = 0; i < table.getRows().getCount(); i++) { // Get the current row tableRow = table.getRows().get(i); // Set the first column cell width to 34% of the page width tableRow.getCells().get(0).setCellWidth((float) (pageWidth * 0.34), CellWidthType.Point); // Set the second column cell width to 33% of the page width tableRow.getCells().get(1).setCellWidth((float) (pageWidth * 0.33), CellWidthType.Point); // Set the third column cell width to 33% of the page width tableRow.getCells().get(2).setCellWidth((float) (pageWidth * 0.33), CellWidthType.Point); } // Save the modified document, specifying the file format as Docx2016 doc.saveToFile("SetColumnWidthsWithFixedValues.docx", FileFormat.Docx_2016); // Close the document doc.close(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
In Word documents, the ability to add, modify, and remove table borders flexibly can significantly enhance readability and professionalism. Firstly, customizing border styles highlights important information, helping readers quickly locate key data or paragraphs and enhancing visual impact. Secondly, by adjusting the thickness, color, and style of border lines, finer design control can be achieved, ensuring a uniform and aesthetically pleasing document style. Lastly, removing unnecessary borders helps reduce visual clutter, making page layouts cleaner and more comprehensible, improving the reading experience. This article will introduce how to add, modify, or remove Word table borders in Java projects using Spire.Doc for Java.
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Java Add Word Table Borders
To uniformly add borders to all cells in a table, you need to visit each cell individually and visually set its border properties. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.loadFromFile() method.
- Retrieve the first section of the document using Document.getSections().get(0).
- Get the first table within the section using Section.getTables().get(0).
- Use a for loop to iterate through all cells in the table.
- Set the cell border to a single line style by using TableCell.getCellFormat().getBorders().setBorderType(BorderStyle.Single).
- Define the border width to 1 point by using TableCell.getCellFormat().getBorders().setLineWidth(1f).
- Set the border color to black by using TableCell.getCellFormat().getBorders().setColor(Color.black).
- Save the changes to the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import java.awt.*; public class AddBorder { public static void main(String[] args) throws Exception{ // Create a new Document object Document doc = new Document(); // Load the document from file doc.loadFromFile("TableExample1.docx"); // Get the first section of the document Section section = doc.getSections().get(0); // Get the first table in the section Table table = section.getTables().get(0); // Declare TableRow and TableCell variables for use in the loop TableRow tableRow; TableCell tableCell; // Iterate through all rows of the table for (int i = 0; i < table.getRows().getCount(); i++) { // Get the current row tableRow = table.getRows().get(i); // Iterate through all cells in the current row for (int j = 0; j < tableRow.getCells().getCount(); j++) { // Get the current cell tableCell = tableRow.getCells().get(j); // Set the border style of the current cell to single line tableCell.getCellFormat().getBorders().setBorderType(BorderStyle.Single); // Set the width of the border tableCell.getCellFormat().getBorders().setLineWidth(1f); // Set the color of the border tableCell.getCellFormat().getBorders().setColor(Color.black); } } // Save the modified document as a new file doc.saveToFile("AddBorders.docx", FileFormat.Docx); // Close the document to release resources doc.close(); } }
Java Modify Word Table Borders
Spire.Doc empowers users with extensive customization options for borders, allowing adjustments such as selecting border styles through TableCell.getCellFormat().getBorders().getBottom().setBorderType(), setting border thickness via TableCell.getCellFormat().getBorders().getBottom().setLineWidth(), and specifying border colors with TableCell.getCellFormat().getBorders().getBottom().setColor(). This enables fine-tuned design of table borders within documents according to personal or project needs. Below are the detailed steps:
- Instantiate a Document object.
- Load a document using the Document.loadFromFile() method.
- Retrieve the first section of the document by calling Document.getSections().get(0).
- Get the first table within the section using Section.getTables().get(0).
- Iterate over the cells in the table that require border style changes using a for loop.
- Change the color of the bottom border to orange by invoking TableCell.getCellFormat().getBorders().getBottom ().setColor(Color.ORANGE).
- Alter the style of the bottom border to a dashed line by calling TableCell.getCellFormat().getBorders().getBottom ().setBorderType(BorderStyle.Dot_Dash).
- Modify the width of the bottom border to 2 points by executing TableCell.getCellFormat().getBorders().getBottom ().setLineWidth(2).
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import java.awt.*; public class ModifyBorder { public static void main(String[] args) { // Create a new Document object Document doc = new Document(); // Load the document from a file doc.loadFromFile("TableExample2.docx"); // Get the first section of the document Section section = doc.getSections().get(0); // Get the first table in that section Table table = section.getTables().get(0); // Declare a TableRow to use within the loop TableRow tableRow; // Iterate through all rows of the table for (int i = 1; i < table.getRows().getCount() - 1; i++) { tableRow = table.getRows().get(i); // Set the border color of the current cell tableRow.getCells().get(1).getCellFormat().getBorders().getBottom().setColor(Color.ORANGE); // Set the border style of the current cell to dotted line tableRow.getCells().get(1).getCellFormat().getBorders().getBottom().setBorderType(BorderStyle.Dot_Dash); // Set the width of the border tableRow.getCells().get(1).getCellFormat().getBorders().getBottom().setLineWidth(2); } // Save the modified document as a new file doc.saveToFile("ModifyBorder.docx", FileFormat.Docx); // Close the document to release resources doc.close(); } }
Java Remove Word Table Borders
When editing Word documents, the flexibility of border design extends beyond the entire table level, allowing for meticulous personalized adjustments at the individual cell level. To comprehensively remove all traces of borders both inside and outside of tables, a phased approach is recommended: Firstly, address the macro-level by clearing the overall border style of the table; subsequently, enter the micro-adjustment phase where each cell within the table is iterated over to revoke its unique border settings. Below are the detailed steps:
- Instantiate a Document object.
- Load a document using the Document.loadFromFile() method.
- Retrieve the first section of the document by calling Document.getSections().get(0).
- Access the first table within the section using Section.getTables().get(0).
- Iterate over all cells in the table using a for loop.
- Remove the border of the table by invoking Table.getTableFormat().getBorders().setBorderType(BorderStyle.None).
- Eliminate the borders of each cell individually by applying TableCell.getCellFormat().getBorders().setBorderType(BorderStyle.None).
- Save the modified document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.BorderStyle; public class RemoveBorder { public static void main(String[] args) { // Create a new Document object Document doc = new Document(); // Load the document from a file doc.loadFromFile("TableExample2.docx"); // Get the first section of the document Section section = doc.getSections().get(0); // Get the first table in the section Table table = section.getTables().get(0); // Remove the borders set on the table table.getTableFormat().getBorders().setBorderType(BorderStyle.None); // Declare a TableRow to use in the loop TableRow tableRow; // Iterate through all rows of the table for (int i = 0; i < table.getRows().getCount(); i++) { tableRow = table.getRows().get(i); for (int j = 0; j < tableRow.getCells().getCount(); j++) { // Remove all borders set on the cell tableRow.getCells().get(j).getCellFormat().getBorders().setBorderType(BorderStyle.None); } } // Save the modified document as a new file doc.saveToFile("RemoveBorder.docx", FileFormat.Docx); // Close the document and release resources doc.close(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Remove Duplicate Values When Merging Cells in Word
2021-10-28 06:58:40 Written by support iceblueSpire.Doc offers Table.applyVerticalMerge() method to merge table cells vertically and Table.applyHorizontalMerge() method to merge table cells horizontally. By default, the merged cells will have repeated values if the cells to be merged contain the same value. This article will demonstrate how to remove repeated values in the merged cells using a customized method with Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Remove Duplicate Values When Merging Cells
The following are the steps to remove the duplicate values in the merged cells in a Word table.
- Create an object of Document class and load the sample document using Document.loadFromFile() method.
- Use Document.getSections() method to get the section collection, and then get the specific section using SectionCollection.get() method.
- Use Section.getTables() method to get the table collection, and then get the desired table using TableCollection.get() method
- Invoke mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end) method to merge table cells vertically or horizontally. This method will determine whether the cells to be merged have the same value, and will preserve only one value in the merged cell.
- Save the document to file using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.interfaces.ITable; public class MergeCells { public static void main(String[] args) throws Exception { //Create an object of Document class and load the sample document. Document document = new Document(); document.loadFromFile("Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Get the first table Table table = section.getTables().get(0); //Invoike mergeCell()method to merge cells vertically mergeCell(table, false, 0, 1, 3); //Invoike mergeCell()method to merge cell horizontally mergeCell(table, true, 0, 4, 5); //Save the document to file document.saveToFile("MergeTable.docx",FileFormat.Docx_2013); } //Customize a mergeCell() method to remove the duplicate values while merging cells public static void mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end) { if (isHorizontalMerge) { //Get a cell from table TableCell firstCell = table.get(index, start); //Invoke getCellText() method to get the cell’s text String firstCellText = getCellText(firstCell); for (int i = start + 1; i <= end; i++) { TableCell cell1 = table.get(index, i); //Check if the text is the same as the first cell if (firstCellText.equals(getCellText(cell1))) { //If yes, clear all the paragraphs in the cell cell1.getParagraphs().clear(); } } //Merge cells horizontally table.applyHorizontalMerge(index, start, end); } else { TableCell firstCell = table.get(start, index); String firstCellText = getCellText(firstCell); for (int i = start + 1; i <= end; i++) { TableCell cell1 = table.get(i, index); if (firstCellText.equals(getCellText(cell1))) { cell1.getParagraphs().clear(); } } //Merge cells vertically table.applyVerticalMerge(index, start, end); } } public static String getCellText(TableCell cell) { StringBuilder text = new StringBuilder(); //Traverse all the paragraphs of a cell for (int i = 0; i < cell.getParagraphs().getCount(); i++) { //Get every paragraph’s text and append it to StringBuilder text.append(cell.getParagraphs().get(i).getText().trim()); } return text.toString(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
This article demonstrates how to align a table in a Word document using Spire.Doc for Java.
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.Table; import com.spire.doc.documents.RowAlignment; public class AlignTable { public static void main(String[] args) { //Create a Document object Document doc=new Document(); //Add a table Table table =doc.addSection().addTable(true); //Set column width table.setColumnWidth(new float[]{100f,150f}); //Set column number and row number table.resetCells(2,2); //Add text to cells table.get(0,0).addParagraph().appendText("Product Code"); table.get(0,1).addParagraph().appendText("Description"); table.get(1,0).addParagraph().appendText("T1052"); table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl"); //Align table to center table.getTableFormat().setHorizontalAlignment(RowAlignment.Center); //Save the document doc.saveToFile("AlignTable.docx", FileFormat.Docx_2013); } }
This article demonstrates how to auto fit a Word table to content or to window, as well as how to fix the cloumn widths, by using Spire.Doc for Java.
Autofit to content
import com.spire.doc.*; public class AutofitToContent { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Add a section Section section = document.addSection(); //Add a table Table table = section.addTable(); table.resetCells(3, 2); //Add content to the cells table.get(0,0).addParagraph().appendText("Product Code"); table.get(0,1).addParagraph().appendText("Description"); table.get(1,0).addParagraph().appendText("T1052"); table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl"); table.get(2,0).addParagraph().appendText("T1062"); table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi"); //Autofit column widths to contents table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents); //Save the document document.saveToFile("AutofitToContent.docx", FileFormat.Docx); } }
Autofit to window
import com.spire.doc.*; public class AutofitToWindow { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Add a section Section section = document.addSection(); //Add a table Table table = section.addTable(); table.resetCells(3, 2); //Add content to the cells table.get(0,0).addParagraph().appendText("Product Code"); table.get(0,1).addParagraph().appendText("Description"); table.get(1,0).addParagraph().appendText("T1052"); table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl"); table.get(2,0).addParagraph().appendText("T1062"); table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi"); //Autofit column widths to window table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); //Save the document document.saveToFile("AutofitToWindow.docx", FileFormat.Docx); } }
Fix column width
import com.spire.doc.*; public class FixColumnWidths { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Add a section Section section = document.addSection(); //Add a table Table table = section.addTable(); table.resetCells(3, 2); //Add content to the cells table.get(0, 0).addParagraph().appendText("Product Code"); table.get(0, 1).addParagraph().appendText("Description"); table.get(1, 0).addParagraph().appendText("T1052"); table.get(1, 1).addParagraph().appendText("AdvoCareSlim Tropical Swirl"); table.get(2, 0).addParagraph().appendText("T1062"); table.get(2, 1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi"); //Set the column widths for (int i = 0; i < table.getRows().getCount(); i++) { table.get(i,0).setCellWidth(80f,CellWidthType.Point); table.get(i,1).setCellWidth(160f,CellWidthType.Point); } //Fix the column widths so that the column width does not increases when the content exceeds the width table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths); //Save the document document.saveToFile("FixColumnWidths.docx", FileFormat.Docx); } }
This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.
import com.spire.doc.AutoFitBehaviorType; import com.spire.doc.Document; import com.spire.doc.Section; import com.spire.doc.Table; import com.spire.doc.fields.DocPicture; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class InsertImageToTableCell { public static void main(String[] args) throws FileNotFoundException { //Create a Document object Document document = new Document(); //Add a section Section section = document.addSection(); //Add a table Table table = section.addTable(true); table.resetCells(2,2); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents); //Load an image to InputStream InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png"); //Insert the image to the cell(0,0) DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream); //Set the width and height of the image picture.setWidth(100); picture.setHeight(100); //Insert another image to the cell(1,1) inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png"); picture = table.get(1,1).addParagraph().appendPicture(inputStream); picture.setWidth(100); picture.setHeight(100); //Save the document document.saveToFile("InsertImgToCell.docx"); } }
This article demonstrates how to insert a nested table in a table cell using Spire.Doc for Java.
import com.spire.doc.*; public class CreateNestedTable { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Add a section Section section = doc.addSection(); //Add a table Table table = section.addTable(true); table.resetCells(2, 3); //Set column width table.getRows().get(0).getCells().get(0).setWidth(50f); table.getRows().get(0).getCells().get(2).setWidth(50f); table.getRows().get(1).getCells().get(0).setWidth(50f); table.getRows().get(1).getCells().get(2).setWidth(50f); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); //Insert content to cells table.get(0,0).addParagraph().appendText("SI.No."); String text = "Earthwork excavation for foundation of buildings, water supply, " + "sanitary lines and electrical conduits either in pits or in " + "trenches 1.5m and above in width, in ordinary soil not exceeding " + "1.5m in depth including dressing the bottom and sides of pits and " + "trenches, stacking the excavated soil clear."; table.get(0,1).addParagraph().appendText(text); table.get(0,2).addParagraph().appendText("Qty"); //Add a nested table to cell(0,1) Table nestedTable = table.get(0,1).addTable(); nestedTable.resetCells(3, 4); nestedTable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents); //Add content to the cells of nested table nestedTable.get(0,0).addParagraph().appendText("SI.No."); nestedTable.get(0,1).addParagraph().appendText("Item"); nestedTable.get(0,2).addParagraph().appendText("Qty"); nestedTable.get(0,3).addParagraph().appendText("Rate"); nestedTable.get(1,0).addParagraph().appendText("1"); nestedTable.get(1,1).addParagraph().appendText("Sand"); nestedTable.get(1,2).addParagraph().appendText("30"); nestedTable.get(1,3).addParagraph().appendText("45"); nestedTable.get(2,0).addParagraph().appendText("2"); nestedTable.get(2,1).addParagraph().appendText("Cement"); nestedTable.get(2,2).addParagraph().appendText("30"); nestedTable.get(2,3).addParagraph().appendText("50"); //Save the document doc.saveToFile("NestedTable.docx", FileFormat.Docx_2013); } }
Tables in Word are a useful feature for organizing and presenting data. While the default table has an equal number of cells in each column or row, there are times when you may need to combine multiple cells to create a header, or split a cell to accommodate additional data. This article will introduce how to programmatically merge or split cells in a Word table using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Merge Table Cells in Word in Java
With Spire.Doc for .NET, you can merge two or more adjacent cells horizontally or vertically using the Table.applyHorizontalMerge() or Table.applyVerticalMerge() method. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.loadFromFile() method.
- Get a specified section in the document using Document.getSections().get() method.
- Add a table to the section using Section.addTable() method.
- Specify the number of rows and columns of the table using Table.resetCells(int rowsNum, int columnsNum) method.
- Horizontally merge specified cells in the table using Table.applyHorizontalMerge(int rowIndex, int startCellIndex, int endCellIndex) method.
- Vertically merge specified cells in the table using Table.applyVerticalMerge(int columnIndex, int startRowIndex, int endRowIndex) method.
- Add some data to the table.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.VerticalAlignment; public class MergeTableCell { public static void main(String[] args) throws Exception { //Create a Document instance Document document = new Document(); //Load a sample Word document document.loadFromFile("input.docx"); //Get the first section Section section = document.getSections().get(0); //Add a 4 x 4 table to the section Table table = section.addTable(true); table.resetCells(4, 4); //Horizontally merge cells 1, 2, 3, and 4 in the first row table.applyHorizontalMerge(0, 0, 3); //Vertically merge cells 3 and 4 in the first column table.applyVerticalMerge(0, 2, 3); //Add some data to the table for (int row = 0; row < table.getRows().getCount(); row++) { for (int col = 0; col < table.getRows().get(row).getCells().getCount(); col++) { TableCell cell = table.get(row, col); cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); Paragraph paragraph = cell.addParagraph(); paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); paragraph.setText("Text"); } } //Save the result document document.saveToFile("MergeTableCells.docx", FileFormat.Docx); } }
Split Table Cells in Word in Java
To divide a cell in a Word table into multiple cells, Spire.Doc for .NET offers the TableCell.splitCell(int columnNum, int rowNum) method. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.loadFromFile() method.
- Get a specified section in the document using Document.getSections().get() method.
- Get a specified table in the section using Section.getTables().get() method.
- Get the table cell that need to be split using Table.getRows().get().getCells().get() method.
- Split the cell into specific number of columns and rows using TableCell.splitCell(int columnNum, int rowNum) method.
- Save the result document using Document.saveToFile() method.
- Java
import com.spire.doc.*; public class SplitTableCell { public static void main(String[] args) throws Exception { //Create a Document instance Document document = new Document(); //Load a sample Word document document.loadFromFile("MergeTableCells.docx"); //Get the first section Section section = document.getSections().get(0); //Get the first table in the section Table table = section.getTables().get(0); //Get the 4th cell in the 4th row TableCell cell1 = table.getRows().get(3).getCells().get(3); //Split the cell into 2 columns and 2 rows cell1.splitCell(2, 2); //save the result document document.saveToFile("SplitTableCells.docx", FileFormat.Docx); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A table is a common way to present tabular data in a Word document. It helps a lot in organizing a big set of information. In this article, you'll learn how to create how to create a table, fill the table with data, and apply formatting to the table cells using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Create a Simple Table in Word
The table below lists some of the core classes and methods responsible for creating as well as formatting a table.
Name | Description |
Table Class | Represents a table in a Word document. |
TableRow Class | Represents a row in a table. |
TableCell Class | Represents a specific cell in a table. |
Section.addTbale() Method | Adds a new table to the specified section. |
Table.resetCells() Method | Resets row number and column number. |
Table.getRows() Method | Gets the table rows. |
TableRow.setHeight() Method | Sets the height of the specified row. |
TableRow.getCells() Method | Returns the cells collection. |
TableRow.getFormat() Method | Gets the format of the specified row. |
The following are the steps to create a simple table in a Word document.
- Create a Document object, and add a section to it.
- Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
- Add a table to the section using Section.addTable() method.
- Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
- Insert data to the rest of the rows, and apply formatting to these rows.
- Save the document to another file using Document.saveToFile() method.
- Java
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) { //Create a Document object Document document = new Document(); //Add a section Section section = document.addSection(); //Define the data for table String[] header = {"Name", "Capital", "Continent", "Area", "Population"}; String[][] data = { new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"}, new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"}, new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"}, new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"}, new String[]{"Chile", "Santiago", "South America", "756943", "13200000"}, new String[]{"Colombia", "Bogota", "South America", "1138907", "33000000"}, new String[]{"Cuba", "Havana", "North America", "114524", "10600000"}, new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"}, new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"}, new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"}, }; //Add a table Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); //Set the first row as table header 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); } //Add data to the rest of rows 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 cells 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)); } } } //Save to file document.saveToFile("output/CreateTable.docx", FileFormat.Docx_2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.