Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,57 @@
# Java-Word-Table-Examples
Create, edit, format, and delete tables in a Word document in Java without Microsoft Word or interop dependencies

This repository contains examples that illustrates how to create, edit, format, and delete tables in Word documents programmatically in Java using [Syncfusion’s Java Word library](https://www.syncfusion.com/word-framework/java/word-library?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) (Essential DocIO) without Microsoft Word or Office interop dependencies.

# Tables in Word documents

You can create, edit, and format simple and nested tables in a Word document. Polish the appearance of tables by applying table styles and conditional formats.

The Syncfusion [Java Word library](https://www.syncfusion.com/word-framework/java/word-library?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) (Essential DocIO) provides comprehensive APIs to create, edit, format, and delete both simple and nested tables in Word documents programmatically in Java and VB.NET. It allows you to customize look of the tables by merging cells, adding or deleting columns or rows, or applying borders, enabling or disabling header rows to repeat on each page or row to break across pages. It generates professional reports with tabular data faster in a batch process without Microsoft Word or Office interop dependencies. The generated reports can be saved as a Word document, HTML, and more.

## Jar files

You can download the jars from the Syncfusion [maven repository](https://jars.syncfusion.com/?_ga=2.177721445.1332356717.1617771042-23317178.1569844681) to use our artifacts in your projects. It helps you to use the Syncfusion Java packages without installing Essential Studio or platform installation to development with Syncfusion controls.

# Key Features

- [Apply built-in table style in Java](applybuiltintablestyles/) - Apply built-in table style to a table in Word document.

- [Modify an existing table style in Java](modifyexistingtablestyle/) - Access an existing table style from a Word document and modify its properties.

- [Create new custom table style in Java](applycustomtablestyles/) - Create new custom table style and apply to a table in Word document.

- [Copy table styles in Java](copytablestyles/) - Copy table styles from one Word document to another.

# Screenshots

**Built-in table style**

<p align="center">
<img src="screenshots/Built-in-table-style.png" alt="Apply built-in table style to a table in Java"/>
</p>

**Custom table style**

<p align="center">
<img src="screenshots/Custom-table-style.png" alt="Create new custom table style and apply to a table in Java"/>
</p>

# Resources

- **Product page:** [Syncfusion Java Word Framework](https://www.syncfusion.com/word-framework/java?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)

- **Documentation:** [Tables in Word document using Syncfusion Java Word library](https://help.syncfusion.com/java-file-formats/word-library/working-with-tables)

- **Online demo:** [Essential DocIO demos](https://github.com/syncfusion/java-demos?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)

- **Download:** [Syncfusion File Formats Controls](https://www.syncfusion.com/sales/products/fileformats?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)

# Support and feedback

* For queries, contact our [Syncfusion support team](https://www.syncfusion.com/support/directtrac/incidents/newincident?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or post the queries through [community forums](https://www.syncfusion.com/forums?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples).

* To renew the subscription, click [here](https://www.syncfusion.com/sales/products?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or contact our sales team at [salessupport@syncfusion.com](mailto:salessupport@syncfusion.com).

# License

This is a commercial product and requires a paid license for possession or use. Syncfusion’s licensed software, including this component, is subject to the terms and conditions of [Syncfusion's EULA](https://www.syncfusion.com/eula/es?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples). You can purchase a license [here](https://www.syncfusion.com/sales/products?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or start a free 30-day trial [here](https://www.syncfusion.com/account/manage-trials/start-trials?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples).
137 changes: 137 additions & 0 deletions applybuiltintablestyles/ApplyBuiltinTableStyles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import java.io.File;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.drawing.ColorSupport;
import com.syncfusion.javahelper.system.io.*;
import com.syncfusion.javahelper.system.xml.*;

public class ApplyBuiltinTableStyles {

public static void main(String[] args) throws Exception {
// Creates new Word document instance and open the word document
WordDocument document = new WordDocument();
// Adds a section to the Word document.
IWSection section = document.addSection();
// Sets the page margin
section.getPageSetup().getMargins().setAll(72);
// Adds a paragraph to the section.
IWParagraph paragraph = section.addParagraph();
paragraph.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
paragraph.getParagraphFormat().setAfterSpacing(20);
IWTextRange textRange = paragraph.appendText("Suppliers");
textRange.getCharacterFormat().setFontSize(14);
textRange.getCharacterFormat().setBold(true);
textRange.getCharacterFormat().setTextColor(ColorSupport.fromArgb(255, 50, 62, 79));
// Modifies the font size to 10 for default paragraph style.
WParagraphStyle style = (WParagraphStyle) document.getStyles().findByName("Normal");
style.getCharacterFormat().setFontSize(10);
// Adds a table to the section.
WTable table = (WTable) section.addTable();
table.resetCells(1, 6);
table.get(0, 0).setWidth(52f);
table.get(0, 0).addParagraph().appendText("Supplier ID");
table.get(0, 1).setWidth(128f);
table.get(0, 1).addParagraph().appendText("Company Name");
table.get(0, 2).setWidth(70f);
table.get(0, 2).addParagraph().appendText("Contact Name");
table.get(0, 3).setWidth(92f);
table.get(0, 3).addParagraph().appendText("Address");
table.get(0, 4).setWidth(66.5f);
table.get(0, 4).addParagraph().appendText("City");
table.get(0, 5).setWidth(56f);
table.get(0, 5).addParagraph().appendText("Country");
// Imports data to the table.
ImportDataToTable(table);
// Applies the built-in table style (Medium Shading 1 Accent 1) to the table.
table.applyStyle(BuiltinTableStyle.MediumShading1Accent1);
// Saves the file
document.save("Result.docx", FormatType.Docx);
document.close();
System.out.println("Word document generated successfully.");
}

private static void ImportDataToTable(WTable table) throws Exception {
FileStreamSupport fs = new FileStreamSupport(getDataDir("Suppliers.xml"), FileMode.Open, FileAccess.Read);
XmlReaderSupport reader = XmlReaderSupport.create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.getNodeType().getEnumValue() != XmlNodeType.Element.getEnumValue())
reader.read();
if (!(reader.getLocalName() == "SuppliersList"))
throw new Exception("Unexpected xml tag " + reader.getLocalName());
reader.read();
while (reader.getNodeType().getEnumValue() == XmlNodeType.Whitespace.getEnumValue())
reader.read();
while (!(reader.getLocalName() == "SuppliersList")) {
if (reader.getNodeType().getEnumValue() == XmlNodeType.Element.getEnumValue()) {
switch (reader.getLocalName()) {
case "Suppliers":
WTableRow tableRow = table.addRow(true);
ImportDataToRow(reader, tableRow);
break;
}
} else {
reader.read();
if ((reader.getLocalName() == "Suppliers")
&& reader.getNodeType().getEnumValue() == XmlNodeType.EndElement.getEnumValue())
break;
}
}
reader.close();
fs.close();
}

private static String getDataDir(String path) {
File dir = new File(System.getProperty("user.dir"));
if (!(dir.toString().endsWith("Java-Word-Table-Examples")))
dir = dir.getParentFile();
dir = new File(dir, "resources");
dir = new File(dir, path);
if (dir.isDirectory() == false)
dir.mkdir();
return dir.toString();
}

private static void ImportDataToRow(XmlReaderSupport reader, WTableRow tableRow) throws Exception {
if (reader == null)
throw new Exception("reader");
while (reader.getNodeType().getEnumValue() != XmlNodeType.Element.getEnumValue())
reader.read();
if (!(reader.getLocalName() == "Suppliers"))
throw new Exception("Unexpected xml tag " + reader.getLocalName());
reader.read();
while (reader.getNodeType().getEnumValue() == XmlNodeType.Whitespace.getEnumValue())
reader.read();
while (!(reader.getLocalName() == "Suppliers")) {
if (reader.getNodeType().getEnumValue() == XmlNodeType.Element.getEnumValue()) {
switch (reader.getLocalName()) {
case "SupplierID":
tableRow.getCells().get(0).addParagraph().appendText(reader.readContentAsString());
break;
case "CompanyName":
tableRow.getCells().get(1).addParagraph().appendText(reader.readContentAsString());
break;
case "ContactName":
tableRow.getCells().get(2).addParagraph().appendText(reader.readContentAsString());
break;
case "Address":
tableRow.getCells().get(3).addParagraph().appendText(reader.readContentAsString());
break;
case "City":
tableRow.getCells().get(4).addParagraph().appendText(reader.readContentAsString());
break;
case "Country":
tableRow.getCells().get(5).addParagraph().appendText(reader.readContentAsString());
break;
default:
reader.skip();
break;
}
} else {
reader.read();
if ((reader.getLocalName() == "Suppliers")
&& reader.getNodeType().getEnumValue() == XmlNodeType.EndElement.getEnumValue())
break;
}
}
}
}
54 changes: 54 additions & 0 deletions applycustomtablestyles/ApplyCustomTableStyles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import java.io.File;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.drawing.ColorSupport;

public class ApplyCustomTableStyles {

public static void main(String[] args) throws Exception {
// Creates new Word document instance and open the word document
WordDocument document = new WordDocument(getDataDir("Table.docx"));
// Adds a new custom table style.
WTableStyle tableStyle = (WTableStyle) document.addTableStyle("CustomStyle");
// Applies formatting for whole table.
tableStyle.getTableProperties().setRowStripe(1);
tableStyle.getTableProperties().setColumnStripe(1);
tableStyle.getTableProperties().getPaddings().setTop(0);
tableStyle.getTableProperties().getPaddings().setBottom(0);
tableStyle.getTableProperties().getPaddings().setLeft(5.4f);
tableStyle.getTableProperties().getPaddings().setRight(5.4f);
// Applies conditional formatting for first row.
ConditionalFormattingStyle firstRowStyle = tableStyle.getConditionalFormattingStyles()
.add(ConditionalFormattingType.FirstRow);
firstRowStyle.getCharacterFormat().setBold(true);
firstRowStyle.getCharacterFormat().setTextColor(ColorSupport.fromArgb(255, 255, 255, 255));
firstRowStyle.getCellProperties().setBackColor(ColorSupport.getBlue());
// Applies conditional formatting for first column.
ConditionalFormattingStyle firstColumnStyle = tableStyle.getConditionalFormattingStyles()
.add(ConditionalFormattingType.FirstColumn);
firstColumnStyle.getCharacterFormat().setBold(true);
// Applies conditional formatting for odd row.
ConditionalFormattingStyle oddRowBandingStyle = tableStyle.getConditionalFormattingStyles()
.add(ConditionalFormattingType.OddRowBanding);
oddRowBandingStyle.getCellProperties().setBackColor(ColorSupport.getWhiteSmoke());
// Gets table to apply style.
WSection section = document.getSections().get(0);
WTable table = section.getTables().get(0);
// Applies the custom table style to the table.
table.applyStyle("CustomStyle");
// Saves and closes the document instance
document.save("Result.docx", FormatType.Docx);
document.close();
System.out.println("Word document generated successfully.");
}

private static String getDataDir(String path) {
File dir = new File(System.getProperty("user.dir"));
if (!(dir.toString().endsWith("Java-Word-Table-Examples")))
dir = dir.getParentFile();
dir = new File(dir, "resources");
dir = new File(dir, path);
if (dir.isDirectory() == false)
dir.mkdir();
return dir.toString();
}
}
40 changes: 40 additions & 0 deletions copytablestyles/CopyTableStyles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.io.File;
import com.syncfusion.docio.*;

public class CopyTableStyles {

public static void main(String[] args) throws Exception {
// Creates new Word document instance and open the word document
WordDocument document = new WordDocument(getDataDir("Table.docx"));
// Creates new Word srcdocument instance and Opens the source Word document
// containing table style definition.
WordDocument srcdocument = new WordDocument(getDataDir("TableStyles.docx"));
// Gets the table style (CustomStyle) from the styles collection.
WTableStyle tableStyle = (WTableStyle) srcdocument.getStyles().findByName("CustomStyle", StyleType.TableStyle);
// Creates a cloned copy of table style.
WTableStyle clonedTableStyle = (WTableStyle) tableStyle.clone();
// Adds the cloned copy of source table style to the destination document.
document.getStyles().add(clonedTableStyle);
srcdocument.close();
// Gets table to apply style.
WSection section = document.getSections().get(0);
WTable table = section.getTables().get(0);
// Adds a new custom table style.
table.applyStyle("CustomStyle");
// Saves the file
document.save("Result.docx", FormatType.Docx);
document.close();
System.out.println("Word document generated successfully.");
}

private static String getDataDir(String path) {
File dir = new File(System.getProperty("user.dir"));
if (!(dir.toString().endsWith("Java-Word-Table-Examples")))
dir = dir.getParentFile();
dir = new File(dir, "resources");
dir = new File(dir, path);
if (dir.isDirectory() == false)
dir.mkdir();
return dir.toString();
}
}
37 changes: 37 additions & 0 deletions modifyexistingtablestyle/ModifyExistingTableStyle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import java.io.File;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.drawing.ColorSupport;

public class ModifyExistingTableStyle {

public static void main(String[] args) throws Exception {
// Creates new Word document instance and open the word document
WordDocument document = new WordDocument(getDataDir("TableModify.docx"));
// Gets the table style (Medium Shading 1 Accent 1) from the styles collection.
WTableStyle tableStyle = (WTableStyle) document.getStyles().findByName("Medium Shading 1 Accent 1",
StyleType.TableStyle);
// Gets the conditional formatting style of the first row (table headers) from
// the table style.
ConditionalFormattingStyle firstRowStyle = tableStyle.getConditionalFormattingStyles()
.get(ConditionalFormattingType.FirstRow);
if (firstRowStyle != null) {
// Modifies the background color for first row (table headers).
firstRowStyle.getCellProperties().setBackColor(ColorSupport.fromArgb(255, 31, 56, 100));
}
// Saves the file
document.save("Result.docx", FormatType.Docx);
document.close();
System.out.println("Word document generated successfully.");
}

private static String getDataDir(String path) {
File dir = new File(System.getProperty("user.dir"));
if (!(dir.toString().endsWith("Java-Word-Table-Examples")))
dir = dir.getParentFile();
dir = new File(dir, "resources");
dir = new File(dir, path);
if (dir.isDirectory() == false)
dir.mkdir();
return dir.toString();
}
}
Loading