DEV Community

Alexis
Alexis

Posted on

Java: How to convert Excel to Word

Microsoft Excel are widely used for storing large amounts of data and Microsoft Word are widely used for creating rich text documents. Sometimes you may need to add the information on Excel workbook into the word document to insert formatted text, images and the other elements in a Word document. In this article, you will learn how to convert Excel files to Word format in Java applications with the help of Spire.Office for Java.

Install Spire.Office for Java

First of all, you're required to add the Spire.Office.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.office</artifactId>
        <version>7.9.9</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

With the help of Spire.Office, you can convert XLS to DOC, XLS to DOCX, XLSX to DOC, and XLSX to DOCX formats easily. You will learn how to save Excel to Word from the following three parts.

Save Excel to Word

Firstly, Spire.Office use Spire.XLS to convert the whole Excel workbook to PDF, and then use Spire.PDF to save PDF as a Word document. By using this way, you only need a few lines to convert Excel to Word.

  • Create a Workbook object and load a sample Excel document using Workbook.loadFromFile() method.
  • Set the Excel to PDF conversion options through the methods under the ConverterSetting object, which is returned by Workbook.getConverterSetting() method.
  • Convert the whole Excel workbook to PDF using Workbook.saveToFile() method.
  • Create a PdfDocument and load the sample PDF file using PdfDocument.loadFromFile() method.
  • Convert the PDF file to Word using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.xls.*;

public class exceltoWord {

    public static void main(String[] args) throws Exception {

        //Create a workbook instance and load the sample Excel
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Set the Excel to PDF conversion options
        workbook.getConverterSetting().setSheetFitToPage(true);

        //Save Excel to PDF
        workbook.saveToFile("ExcelToPdf.pdf", com.spire.xls.FileFormat.PDF);

        //Load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("ExcelToPdf.pdf");

        //Save PDF to Word
        pdf.saveToFile("ExcelToWord1.docx", com.spire.pdf.FileFormat.DOCX);

    }
}
Enter fullscreen mode Exit fullscreen mode

Excel to Word

Java Excel to Word

Spire.Office use Spire.XLS to convert a specific Excel worksheet to HTML, and then use Spire.Doc to save HTML as a Word document.

  • Create a Workbook object and load a sample Excel file using Workbook.loadFromFile() method.
  • Get a specific worksheet using Workbook.getWorksheets().get() method.
  • Set the Excel to HTML conversion options.
  • Save Excel to HTML using Worksheet.saveToHtml() method.
  • Create a Document instance and load the sample HTML using Document.loadFromFile() method.
  • Save the document to a Word file using Document.saveToFile() method.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.XHTMLValidationType;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class exceltoWord {

    public static void main(String[] args) throws Exception {

        //Create a workbook instance and load the sample
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Set the Excel to HTML conversion options
        worksheet.getAllocatedRange().autoFitColumns();
        worksheet.getAllocatedRange().autoFitRows();

        //Save Excel worksheet to HTML
        worksheet.saveToHtml("ExcelToHtml.html");

        //Create a document instance and load the sample HTML File
        Document document = new Document();
        document.loadFromFile("ExcelToHtml.html", FileFormat.Html, XHTMLValidationType.None);

        //Save the document to a Word file
        document.saveToFile("ExcelToWord2.docx",FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Excel to Word

Convert Excel to Word

Spire.Office use Spire.XLS to Extract all the data, image and styles on the Excel workbook, and then use Spire.Doc to add all the elements to the word table.

  • Create a Workbook object and load a sample Excel 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.
  • Extract the picture from the Excel using ExcelPicture.getPicture() method and get the height and width of the picture.
  • Add the picture to the word table cell and set the width and height of the picture.
  • Detect the merged cells in the worksheet and merge the corresponding cells of the Word tale using the custom method mergeCells().
  • Get value of a specific Excel cell using CellRange.getValue() method and add it to a cell of the Word table using TableCell.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.
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.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

public class exceltoWord {

    public static void main(String[] args) throws Exception {

        //Create a workbook instance and load the sample Excel
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Create a document instance and add a section to it
        Document doc = new Document();
        Section section = doc.addSection();
        section.getPageSetup().setOrientation(PageOrientation.Landscape);

        //Add a table to Word
        Table table = section.addTable(true);
        table.resetCells(sheet.getLastRow(), sheet.getLastColumn());

        //Extract the picture from the Excel
        ExcelPicture pic = sheet.getPictures().get(0);
        BufferedImage loImage = pic.getPicture();
        ImageIO.write(loImage,"jpg",new File("Image.jpg"));

        //load the image and get its width and height
        File file = new File("image.jpg");
        FileInputStream inputStream = new FileInputStream(file);
        BufferedImage image = ImageIO.read(file);
        int width= image.getWidth();
        int height = image.getHeight();

        //Add the picture to the word table cell and set the width and height
        DocPicture picture = table.getRows().get(1).getCells().get(3).addParagraph().appendPicture(inputStream);
        picture.setWidth(width);
        picture.setHeight(height);

        //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("ExcelToWord3.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;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Excel to Word

Conclusion

In this article, you have learned how to convert Excel files to Word format in Java applications. With Spire.Office for java, you can also convert Word to Excel, Word to PDF, Excel to PDF, PowerPoint to PDF etc. You can get more information from Office operation page here.

Top comments (2)

Collapse
 
_bkeren profile image
''

i know it is paid product, isn't it ?

Collapse
 
behrjozef profile image
Jozef Behr

Thank you for sharing this , i have no idea about this that why i was searching for the same.

Thank You,
Jozef Behr