Export Excel Data to Word Tables with Formatting in Java
When making reports in Word, we often need to copy and paste data from Excel into Word, so that we can view the data directly in the Word document without opening another Excel file. However, if the table is relatively long, the content will be lost to a certain extent, and the data cannot be displayed completely. It will take a lot of time and effort to complete the entire process when there is a lot of work. So how can we easily export Excel data to Word tables with formatting? Don't worry, this article will detail how to import formatted Excel data into a Word table through a Java application. I hope you can find this article useful. The code is only for reference.
Programming Environment
Method 1:
Introduced manually. Download Free
Spire.Office for Java locally, unzip it, and find the Spire.Office.jar file in
the lib folder. Open the following interface in IDEA, and import the jar file
in the local path into the Java program:
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.office.free</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>
Export Excel Data to a Word Table with Formatting
Create a Workbook object and load a sampleExcel file using Workbook.loadFromFile() method.Get a specific worksheet using Workbook.getWorksheets().get() method.
Create a Document object, and add a section to it.
Add a table using Section.addTable() method.
Detect the merged cells in the worksheet
and merge the corresponding cells of the Word tale using the custom methodmergeCells().Get value of a specific Excel cell using
CellRange.getValue() method and add it to a cell of the Word table usingTableCell.addParagraph().appendText() method.Copy the font style and cell style from
Excel to the Word table using the custom method copyStyle().
Save the document to a Word file using Document.saveToFile() method.
Full Code
import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.PageOrientation;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;
public class ExportExcelToWord {
public static void main(String[] args) {
//Load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Create a Word document
Document doc = new Document();
Section section = doc.addSection();
section.getPageSetup().setOrientation(PageOrientation.Landscape);
//Add a table
Table table = section.addTable(true);
table.resetCells(sheet.getLastRow(), sheet.getLastColumn());
//Merge cells
mergeCells(sheet, table);
for (int r = 1; r <= sheet.getLastRow(); r++) {
//Set row Height
table.getRows().get(r - 1).setHeight((float) sheet.getRowHeight(r));
for (int c = 1; c <= sheet.getLastColumn(); c++) {
CellRange xCell = sheet.getCellRange(r, c);
TableCell wCell = table.get(r - 1, c - 1);
//Get value of a specific Excel cell and add it to a cell of Word table
TextRange textRange = wCell.addParagraph().appendText(xCell.getValue());
//Copy font and cell style from Excel to Word
copyStyle(textRange, xCell, wCell);
}
}
//Save the document to a Word file
doc.saveToFile("ExportToWord.docx", FileFormat.Docx);
}
//Merge cells if any
private static void mergeCells(Worksheet sheet, Table table) {
if (sheet.hasMergedCells()) {
//Get merged cell ranges from Excel
CellRange[] ranges = sheet.getMergedCells();
for (int i = 0; i < ranges.length; i++) {
int startRow = ranges[i].getRow();
int startColumn = ranges[i].getColumn();
int rowCount = ranges[i].getRowCount();
int columnCount = ranges[i].getColumnCount();
//Merge corresponding cells in Word table
if (rowCount > 1 && columnCount > 1) {
for (int j = startRow; j <= startRow + rowCount ; j++) {
table.applyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
}
table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
}
if (rowCount > 1 && columnCount == 1 ) {
table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
}
if (columnCount > 1 && rowCount == 1 ) {
table.applyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount-1);
}
}
}
}
//Copy cell style of Excel to Word table
private static void copyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell) {
//Copy font style
wTextRange.getCharacterFormat().setTextColor(xCell.getStyle().getFont().getColor());
wTextRange.getCharacterFormat().setFontSize((float) xCell.getStyle().getFont().getSize());
wTextRange.getCharacterFormat().setFontName(xCell.getStyle().getFont().getFontName());
wTextRange.getCharacterFormat().setBold(xCell.getStyle().getFont().isBold());
wTextRange.getCharacterFormat().setItalic(xCell.getStyle().getFont().isItalic());
//Copy backcolor
wCell.getCellFormat().setBackColor(xCell.getStyle().getColor());
//Copy horizontal alignment
switch (xCell.getHorizontalAlignment()) {
case Left:
wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
break;
case Center:
wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
break;
case Right:
wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
break;
}
//Copy vertical alignment
switch (xCell.getVerticalAlignment()) {
case Bottom:
wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Bottom);
break;
case Center:
wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
break;
case Top:
wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Top);
break;
}
}
}Effective Shot
Conclusion:
In this post, you have learned how to merge or unmerge cells in Excel in Java.
Comments
Post a Comment