Java: Delete Blank Rows, Columns and Cells from Excel

When importing data from a database into Excel, you may encounter blank rows, columns or cells in the result file. The presence of blank rows, columns, or cells in Excel can be a visual annoyance. More importantly, it may let Excel misunderstand data ranges and cause errors when applying certain functions. In this article, I will demonstrate how to delete blank rows, columns and cells from Excel using Java.

Add Dependencies

This article uses Free Spire.XLS for Java to detect and remove blank rows, columns and cells from Excel. Before coding, you need to add needed dependencies for including Free Spire.XLS 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 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.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Method 2: If you are not using maven, you can download the JAR file from the official website, extract the zip file and then import the Spire.Xls.jar file under the lib folder into your project as a dependency.

Delete Blank Rows from Excel in Java

The following are the steps to delete blank rows in Excel:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet that contains blank rows using Workbook.getWorksheets().get(sheetIndex) method.
  • Loop through all rows in the worksheet.
  • Check if the current row is blank or not using Worksheet.getRows()[rowIndex].isBlank() method. If the result is true, remove it using Worksheet.deleteRow(rowIndex) method. Note the row index here is 1-based.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteBlankRows {
    public static void main(String []args){
        //Instantiate a Workbook object
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Sample2.xlsx");

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

        //Loop through all rows in the worksheet
        for (int i = sheet.getRows().length - 1; i >= 0; i--)
        {
            //Check if the current row is blank
            if (sheet.getRows()[i].isBlank())
            {
                //Delete the blank row
                sheet.deleteRow(i + 1); 
            }
        }
        
        //Save the result file
        workbook.saveToFile("DeleteBlankRows.xlsx", ExcelVersion.Version2013);
    }
}
Delete Blank Rows from Excel using Java

Delete Blank Columns from Excel in Java

The following are the steps to delete blank columns from Excel:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet that contains blank columns using Workbook.getWorksheets().get(sheetIndex) method.
  • Loop through all columns in the worksheet.
  • Check if the current column is blank or not using Worksheet.getColumns()[columnIndex].isBlank() method. If the result is true, remove it using Worksheet.deleteColumn(columnIndex) method. Note the column index here is 1-based.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteBlankColumns {
    public static void main(String []args){
        //Instantiate a Workbook object
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Sample2.xlsx");

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

        //Loop through all rows in the worksheet
        for (int i = sheet.getColumns().length - 1; i >= 0; i--)
        {
            //Check if the current row is blank
            if (sheet.getColumns()[i].isBlank())
            {
                //Delete the blank row
                sheet.deleteColumn(i + 1);
            }
        }

        //Save the result file
        workbook.saveToFile("DeleteBlankColumns.xlsx", ExcelVersion.Version2013);
    }
}
Delete Blank Columns from Excel using Java

Delete Blank Cells from Excel in Java

The following are the steps to delete blank cells from Excel:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the worksheet that contains blank cells using Workbook.getWorksheets().get(sheetIndex) method.
  • Loop through the rows and columns in the worksheet.
  • Access the current cell using Worksheet.getCellRange(rowIndex, columnIndex) method. Note the row index and column index here are 1-based.
  • Check if the current cell is blank or not using CellRange.isBlank() method. If the result is true, remove it using Worksheet.deleteRange(CellRange, DeleteOption) method.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.*;

public class DeleteBlankCells {
    public static void main(String []args){
        //Instantiate a Workbook object
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Sample1.xlsx");

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

        //Get the row count
        int maxRow = sheet.getRows().length;
        //Get the column count
        int maxColumn = sheet.getColumns().length;

        //Loop through the rows and columns
        for (int i = maxRow - 1; i >= 0; i--)
        {
            for (int j = maxColumn - 1; j >= 0; j--)
            {
                //Get the current cell
                CellRange cell = sheet.getCellRange(i + 1, j + 1);
                //Determine if the cell is blank or not
                if (cell.isBlank())
                {
                    //Remove the blank cell with DeleteOption (MoveLeft/MoveUp)
                    sheet.deleteRange(cell, DeleteOption.MoveLeft);
                }
            }
        }

        //Save the result file
        workbook.saveToFile("DeleteBlankCells.xlsx", ExcelVersion.Version2013);
    }
}
Delete Blank Cells from Excel using Java

Convert XLS to XLSX or XLSX to XLS using Java

About XLS and XLSX

Both XLS and XLSX are Microsoft Excel file formats. XLS is a binary file format generated by Microsoft Excel 2003 and older versions. Compared with XLSX, XLS is more compatible because it can be read by all versions of Microsoft Excel.

XLSX is a Microsoft Office OpenXML-based format generated by Microsoft Excel 2007 and newer versions. XLSX files can contain more rows and columns than XLS files, but they are only readable by Excel 2007 and newer versions.

Java Library to Convert XLS to XLSX or XLSX to XLS

In this article, the library used to convert XLS to XLSX or XLSX to XLS in Java is Spire.XLS for Java.

If you are using maven, you can install Spire.XLS for Java from maven by adding the following configurations to your project’s pom.xml.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.xls</artifactId>    
        <version>12.7.4</version>    
    </dependency>    
</dependencies>

If you are not using maven, you can download the latest version of Spire.XLS for Java from the official website, extract the package and then import Spire.Xls.jar in the lib folder into your project as a dependency.

Convert XLS to XLSX in Java

You can convert an XLS file to XLSX format easily by using the Workbook.saveToFile(String, FileFormat) method. The following are the detailed steps:

  • Initialize an instance of Workbook class.
  • Load the XLS file using Workbook.loadFromFile() method.
  • Save the file to XLSX format using Workbook.saveToFile(String, FileFormat) method.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class ConvertXlsToXlsx {
    public static void main(String[] args){
        //Initialize an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load the XLS file
        workbook.loadFromFile("Sample.xls");
        
        //Save the XLS file to XLSX format
        workbook.saveToFile("ToXlsx.xlsx", FileFormat.Version2016);
    }
}

Convert XLSX to XLS in Java

The Workbook.saveToFile(String, FileFormat) method can also be used to convert an XLSX file to XLS format. The steps are almost the same with that of converting XLS to XLSX:

  • Initialize an instance of Workbook class.
  • Load the XLS file using Workbook.loadFromFile() method.
  • Save the file to XLSX format using Workbook.saveToFile(String, FileFormat) method.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class ConvertXlsxToXls {
    public static void main(String[] args){
        //Initialize an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load the XLSX file
        workbook.loadFromFile("Sample.xlsx");

        //Save the XLSX file to XLS format
        workbook.saveToFile("ToXls.xls", FileFormat.Version97to2003);
    }
}

Conclusion

This article introduced how to convert XLS to XLSX or vice versa in Java using the Workbook.saveToFile() method provided by Spire.XLS for Java library. In addition to converting XLS to XLSX, you can also use the Workbook.saveToFile() method to convert from XLS or XLSX to other spreadsheet formats (such as XLSM, XLSB, ODS, UOS, ET and ETT) or other file formats (such as PDF, HTML, CSV, OpenXML, PCL and XPS).

Convert Excel to CSV or CSV to Excel using Java

Excel and CSV are two of the popular file formats for storing tabular data. The difference between them is that Excel is a binary file format that holds information about all the worksheets in a workbook including both content and formatting, while CSV is a simple type of plain text file in which values are separated by commas. Sometimes, developers may need to do conversions between Excel and CSV. In this article, I will introduce how to convert Excel to CSV or CSV to Excel using Java.

Add Dependencies

To implement the conversions between Excel and CSV, this article uses Spire.XLS for Java.

You can either download the library’s jar from the official website or install it from Maven by adding the following code to your maven-based 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.xls </artifactId>    
        <version>12.6.0</version>    
    </dependency>    
</dependencies>

Convert Excel XLS or XLSX to CSV using Java

You can convert a specific worksheet or all worksheets in an Excel workbook as CSV. The following steps show you how to convert a specific worksheet to CSV:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile(filePath) method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get(sheetIndex) method.
  • Save the worksheet as CSV using Worksheet.saveToFile(filePath, separator) method.
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Save the worksheet as CSV
        sheet.saveToFile("ExcelToCSV.csv", ",");
    }
}
Convert Excel to CSV using Java

If you want to convert all worksheets in an Excel workbook as separate CSV files, you need to loop through each worksheet in the workbook, then call Worksheet.saveToFile(string fileName, string separator) method to save the worksheet as CSV, as shown in the following example.

Convert Multiple Worksheets to Separate CSV Files using Java

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Loop through the worksheets in the file
        for(int i = 0; i< workbook.getWorksheets().getCount(); i++) {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Save each worksheet as separate CSV
            sheet.saveToFile("ExcelToCSV_" + i + ".csv", ",");
        }
    }
}

Convert CSV to Excel XLS or XLSX using Java

A CSV file can also be converted to Excel. The following are the steps to do so:

  • Create an instance of Workbook class.
  • Load a CSV file using Workbook.loadFromFile(filePath, separator) method.
  • Loop through the worksheets in the CSV file.
  • In the loop, access the used range of the current worksheet using Worksheet.getAllocatedRange() method, and set ignore error option using CellRange.setIgnoreErrorOptions() method. Then autofit columns and rows using CellRange.autoFitColumns() and CellRange.autoFitRows() methods.
  • Save the CSV to Excel using Workbook.saveToFile(filePath, ExcelVersion) method.
import com.spire.xls.*;

import java.util.EnumSet;

public class ConvertCsvToExcel {
    public static void main(String []args) {
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load a CSV file
        workbook.loadFromFile("ExcelToCSV.csv", ",");

        //Loop through the worksheets in the CSV file
        for (int i = 0; i < workbook.getWorksheets().getCount(); i++)
        {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Access the used range in each worksheet
            CellRange usedRange = sheet.getAllocatedRange();
            //Ignore errors when saving numbers in the used range with text
            usedRange.setIgnoreErrorOptions(EnumSet.of(IgnoreErrorType.NumberAsText));
            //Autofit columns and rows
            usedRange.autoFitColumns();
            usedRange.autoFitRows();
        }

        //Save the CSV file as Excel .xlsx file
        workbook.saveToFile("CSVToExcel.xlsx", ExcelVersion.Version2013);
    }
}
Convert CSV to Excel using Java

Convert Excel to CSV and Vice Versa in Java

CSV files are comma separated values files in which data are stored as plain text. They are generally faster and consume less memory than Excel files. In some cases, you may be asked to convert Excel files to CSV for quick data import. This article will demonstrate how to convert Excel to CSV and vice versa in Java using Free Spire.XLS for Java API.

Add Dependencies

Method 1: If you are using 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.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Method 2: If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Xls.jar file under the lib folder into your project as a dependency.

Convert Excel to CSV in Java

The Worksheet class of Free Spire.XLS exposes a saveToFile() method which allows developers to easily convert a specific Excel worksheet as CSV.

The following are the steps to convert a specific worksheet as CSV:

  • Create an instance of a Workbook class.
  • Load the Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index.
  • Call Worksheet.saveToFile() method to save the worksheet as CSV.

Code example:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Save the worksheet as CSV
        sheet.saveToFile("ExcelToCSV.csv", ",");
    }
}
Convert Excel worksheet to CSV using Java

If you want to save multiple worksheets in an Excel file as separate CSV files, you need to loop through the worksheets and then save each worksheet as a CSV file. Refer to the code example below:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Loop through the worksheets in the file
        for(int i = 0; i< workbook.getWorksheets().getCount(); i++) {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Save each worksheet as separate CSV 
            sheet.saveToFile("ExcelToCSV_" + i + ".csv", ",");
        }
    }
}

Convert CSV to Excel in Java

To convert a CSV file to Excel file, you will need to load the CSV file using loadFromFile() method of Workbook class, then call the saveToFile() method of Workbook class to save it as Excel.

The following are the steps to convert a CSV to Excel:

  •  Create an instance of a Workbook class.
  • Load the CSV file using Workbook.loadFromFile() method.
  • Loop through the worksheets in the CSV file. Get the used range of each worksheet using Worksheet.getAllocatedRange() method, then ignore errors when setting numbers in the range of cells as text using CellRange.setIgnoreErrorOptions() method.
  • Save the CSV file as an Excel .xlsx file using Workbook.saveToFile() method.

Code example:

import com.spire.xls.*;

import java.util.EnumSet;

public class ConvertCsvToExcel {
    public static void main(String []args) {
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load a CSV file
        workbook.loadFromFile("ExcelToCSV.csv", ",");

        //Loop through the worksheets in the CSV file
        for (int i = 0; i < workbook.getWorksheets().getCount(); i++)
        {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Access the used range in each worksheet
            CellRange usedRange = sheet.getAllocatedRange();
            //Ignore errors when setting numbers in the used range as text
            usedRange.setIgnoreErrorOptions(EnumSet.of(IgnoreErrorType.NumberAsText));
            //Autofit columns and rows
            usedRange.autoFitColumns();
            usedRange.autoFitRows();
        }

        //Save the CSV file as Excel .xlsx file
        workbook.saveToFile("CSVToExcel.xlsx", ExcelVersion.Version2013);
    }
}
Convert CSV to Excel using Java

Add or Delete Page Breaks in Excel in Java

Page breaks in Excel are dividers that break a large worksheet into separate pages for printing. By default, Excel inserts automatic page breaks according to the paper size and margin settings etc. But you can divide the worksheet at specific places you want by inserting manual page breaks. In this article, I will demonstrate how to add or delete manual page breaks in Excel in Java using Free Spire.XLS for Java API.

Contents Summary:

  • Add Page Breaks to Excel in Java
  • Delete a Specific Page Break from Excel in Java
  • Delete All Page Breaks from Excel in Java

Add Dependencies

To begin with, you need to add needed dependencies for including Free Spire.XLS for Java library into your Java project. You can either download the library’s jar from the official website or install it from Maven by adding the following code to your maven-based 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

Add Page Breaks to Excel in Java

You can add two types of page breaks: Horizontal page break and vertical page break.

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Specify the cells where you want to add page breaks to using Worksheet.getRange().get() method.
  • Add horizontal and vertical page breaks to the cells using Worksheet.getHPageBreaks().add() and Worksheet.getVPageBreaks().add() methods.
  • Set the sheet view mode to ViewMode.Preview using Worksheet.setViewMode() method.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.*;

public class AddPageBreaks {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Specify the cells where you want to add page breaks to
        CellRange cell1 = sheet.getRange().get("A10");
        CellRange cell2 = sheet.getRange().get("F1");

        //Add a horizontal page break
        sheet.getHPageBreaks().add(cell1);

        //Add a vertical page break
        sheet.getVPageBreaks().add(cell2);

        //Set view mode to Preview in order to view the page breaks
        sheet.setViewMode(ViewMode.Preview);

        //Save the result file
        workbook.saveToFile("AddPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}
Add page breaks to Excel using Java

Delete a Specific Page Break from Excel in Java

The following are the steps to delete a specific horizontal or vertical page break from an Excel worksheet:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Delete a specific horizontal or vertical page break from the worksheet by its index using Worksheet.getHPageBreaks().removeAt() or Worksheet.getVPageBreaks().removeAt() method.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteASpecificPageBreak {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("AddPageBreaks.xlsx");

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

        //Delete the first horizontal page break
        sheet.getHPageBreaks().removeAt(0);
        //Delete the first vertical page break
        sheet.getVPageBreaks().removeAt(0);

        //Save the result file
        workbook.saveToFile("DeleteASpecificPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}

Delete All Page Breaks from Excel in Java

To delete all the page breaks, you can follow the steps below:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Delete all the horizontal and vertical page breaks from the worksheet using Worksheet.getHPageBreaks().clear() and Worksheet.getVPageBreaks().clear() methods.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteAllPageBreaks {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("AddPageBreaks.xlsx");

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

        //Delete all horizontal page breaks
        sheet.getHPageBreaks().clear();
        //Delete all vertical page breaks
        sheet.getVPageBreaks().clear();

        //Save the result file
        workbook.saveToFile("DeleteAllPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}

Note: Deleting the manual page breaks will reset the worksheet to display the automatic page breaks (In Page Break Preview, dashed lines are page breaks Excel automatically added. Solid lines are page breaks that were added manually).

Delete page breaks from Excel using Java

See More

Product Page | Tutorials | Forum |

Identify Merged Cells in Excel in Java

When there are merged cells in your worksheet, you may experience problems performing certain operations, such as sorting data. For such cases, Microsoft Excel provides a built-in feature – “Find and Replace” – that allows you to find merged cells within a worksheet. Once the merged cells are found, you can process them further, for example, highlighting them or unmerging them. In this article, I will demonstrate how to achieve this task programmatically in Java using Free Spire.XLS for Java API.

Add Dependencies

To begin with, you need to add needed dependencies for including Free Spire.XLS for Java library into your Java project. You can either download the library’s jar from the official website or install it from Maven by adding the following code to your maven-based 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

Identify Merged Cells in Excel

The following are the steps to identify merged cells in an Excel worksheet:

  • Create an instance of Workbook class and load the Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet using Workbook.getWorksheets().get() method.
  • Get the merged range of cells into a CellRange array using Worksheet.getMergedCells() method.
  • Loop through the array, highlight the merged cells using CellRange.getCellStyle().setColor() method.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import java.awt.*;

public class IdentifyMergedCells {
    public static void main(String []args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile( "Input.xlsx");

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

        //Get the merged cell ranges in the worksheet into a CellRange array
        CellRange[] range = sheet.getMergedCells();

        //Traverse through the array
        for(CellRange cell : range){
            //Highlight the merged cells
            cell.getCellStyle().setColor(Color.YELLOW);

            //Unmerge the merged cells
            //cell.unMerge();
        }

        //Save the result file
        workbook.saveToFile("IdentifyMergedCells.xlsx", ExcelVersion.Version2013);
    }
}

The result file after highlighting merged cells:

Identify Merged Cells in Excel in Java

See Also: Merge and Unmerge Excel Cells in Java

Merge and Unmerge Excel Cells in Java

In Microsoft Excel, you can easily combine two or more cells into a single cell by clicking the “Merge and Center” button, you can also unmerge them into separate cells by clicking the button again. In this article, I will introduce how to implement this task programmatically in Java using Free Spire.XLS for Java API.

Add Dependencies

If you use maven, specify the following dependencies for Free Spire.XLS for Java API in 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

For non-maven projects, download Free Spire.XLS for Java pack from the official website and add Spire.Xls.jar in the lib folder into your project as a dependency.

Merge and Unmerge Cells

The following are the steps to merge or unmerge cells in an Excel file:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet using Workbook.getWorksheets().get() method.
  • Get the desired range of cells using Worksheet.getRanges().get() method.
  • Merge or unmerge the cells using XlsRange.merge() or XlsRange.unMerge() method.
  • Save the result file using Workbook.saveToFile() method.
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class MergeAndUnmergeCells {
    public static void main(String []args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Template.xlsx");

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

        //Get the desired range of cells
        CellRange range = worksheet.getRange().get("A1:E1");
        //Merge the cells
        range.merge();

        //Get the desired range of cells
        range = worksheet.getRange().get("A3:A7");
        //Unmerge the cells
        range.unMerge();

        //Merge a specific (seventh) column
        //worksheet.getColumns()[6].merge();

        //Save the result file
        workbook.saveToFile("MergeAndUnmergeCells.xlsx", ExcelVersion.Version2013);
    }
}
Merge and Unmerge Excel Cells in Java

See Also: Identify Merged Cells in Excel in Java

Read Values from Formulas in Excel in Java

Introduction

When reading Excel files, you may come across situations where one or more cells contain formulas instead of raw data. For such cases, this article will demonstrate how to read data (including formulas and the actual values) from these cells programmatically in Java using Free Spire.XLS for Java library.

Add Dependencies

If you use maven, specify the following dependencies for Free Spire.XLS for Java library in 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

For non-maven projects, download Free Spire.XLS for Java pack from the official website and add Spire.Xls.jar in the lib folder into your project as a dependency.

Read Formulas and the Actual Values

To read formulas, you can use the CellRange.getFormula() method. To get actual values from formulas, you can use the CellRange.getFormulaValue() method.

The following are the steps to read all of the formulas and the actual values from an Excel file:

  • Create a Workbook instance and load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet using Workbook.getWorksheets.get() method.
  • Loop through the rows and columns in the worksheet.
  • Get the current cell using Worksheet.getCellRange(int row, int column) method.
  • Detect if the cell has formula using CellRange.hasFormula() method, if yes, get the formula using CellRange.getFormula() method and the actual values using CellRange.getFormulaValue() method.
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ReadFormulasAndActualValues {
    public static void main(String []args){
        
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Formulas.xlsx");

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

        //Get the row count
        int maxRow = sheet.getLastRow();
        //Get the column count
        int maxColumn = sheet.getLastColumn();

        //Loop through the rows
        for (int row = 1; row <= maxRow; row++)
        {
            //Loop through the columns
            for (int col = 1; col <= maxColumn; col++)
            {
                //Get the current cell
                CellRange cell = sheet.getCellRange(row, col);
                //Detect if the cell has formula
                if(cell.hasFormula()) {
                    //Print out the formula and the actual data value
                    System.out.print("Formula: " + cell.getFormula() + "\t\t" +  "Value: " + cell.getFormulaValue().toString() + "\t\t");
                }
            }
            System.out.print("\n");
        }
    }
}

Output:

Read formulas and the actual values from Excel in Java

Create Combo Chart in Excel in Java

Combo chart, also known as combination chart, is a combination of two or more chart types. You can use it to display different types of information on a single graphic, for example, actual expenses against budget. In this article, I will demonstrate how to create a combo chart in Excel programmatically in Java using Free Spire.XLS for Java library.

Add Dependencies

To begin with, you need to add needed dependencies for including Free Spire.XLS for Java library into your Java project. You can either download the library’s jar from the official website or install it from Maven by adding the following code to your maven-based 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

Create a Combo Chart

To create a combo chart, you need to make sure your worksheet has at least two data series. Besides, you can create a combo chart with just a single Y axis, as well as with two Y axes.

The following are the steps to create a combo chart with two Y axes.

  1. Create a Workbook instance and load an Excel file using Workbook.loadFromFile() method.
  2. Get the desired worksheet using Workbook.getWorksheets().get() method.
  3. Add a chart to the worksheet using Worksheet.getCharts.add() method, then set chart title, data range and location.
  4. Get the data series of the chart using Chart.getSeries().get() method, and apply different chart types to different data series using ChartSerie.setSerieType() method.
  5. Add a secondary Y axis for a desired data series using ChartSerie.setUsePrimaryAxis(false) method.
  6. Save the Excel file using Workbook.saveToFile() method.
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;

public class CreateComboChart {
    public static void main(String []args){

        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load a sample Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Add a chart based on the data from A2 to C7
        Chart chart = sheet.getCharts().add();
        chart.setChartTitle("Combo Chart");
        chart.setDataRange(sheet.getCellRange("A2:C7"));
        chart.setSeriesDataFromRange(false);

        //Set position of the chart
        chart.setLeftColumn(6);
        chart.setTopRow(2);
        chart.setRightColumn(14);
        chart.setBottomRow(15);

        //Apply different chart types to different data series
        ChartSerie cs1 = (ChartSerie)chart.getSeries().get(0);
        cs1.setSerieType(ExcelChartType.ColumnClustered);
        ChartSerie cs2 = (ChartSerie)chart.getSeries().get(1);
        cs2.setSerieType(ExcelChartType.LineMarkers);

        //Add a secondary Y axis to the chart
        cs2.setUsePrimaryAxis(false);

        //Save the file
        workbook.saveToFile("ComboChart.xlsx", ExcelVersion.Version2013);
    }
}

The created Combo chart:

Create Combo chart in Excel in Java

Merge Multiple Excel Workbooks or Worksheets into One in Java

Introduction

When processing data in Excel, you may encounter a situation where your data is spread across multiple workbooks or worksheets. It would be better to merge the workbooks or worksheets into one instead of switching between different sources. In this article, I will introduce how to achieve this function programmatically in Java using Free Spire.XLS for Java library.

Add Dependencies

To begin with, you need to add needed dependencies for including Free Spire.XLS for Java library into your Java project. You can either download the library’s jar from this link or install it from Maven by adding the following code to your maven-based 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.xls.free</artifactId>    
        <version>3.9.1</version>    
    </dependency>    
</dependencies>

Merge Multiple Excel Worksheets into One

Free Spire.XLS for Java allows you to merge multiple worksheets into a single worksheet by copying cell ranges using the CellRange.copy(CellRange destRange) method. Data and formatting will be copied with high precision.

You can merge worksheets in the same or different workbooks into one. In the following code example, you will see how to merge two Excel worksheets in the same workbook into a single worksheet:

import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

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

        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");
        
        //Get the first worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);
        //Get the second worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);
        
        //Specify the source range (used range) in the second worksheet
        CellRange sourceRange = sheet2.getAllocatedRange();
        //Specify the destination range in the first worksheet
        CellRange destRange = sheet1.getRange().get(sheet1.getLastRow() +1, 1);

        //Copy data along with formatting from the source range to the destination range
        sourceRange.copy(destRange);

        //Save the resultant file
        workbook.saveToFile("MergeWorksheets.xlsx", ExcelVersion.Version2013);
    }
}

Merge Multiple Excel Workbooks into One

The library enables you to merge multiple workbooks into one by copying the worksheets in different workbooks into a single workbook using the XlsWorksheetsCollection.addCopy() method.

The following code example shows how to merge two workbooks into one:

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import com.spire.xls.WorksheetCopyType;

public class MergeWorkbooks {
    public static void main(String []args) throws Exception {
        //Create a String array for Excel workbooks
        String[] inputFiles = new String[]{"file1.xlsx","file2.xlsx"};

        //Create a new workbook
        Workbook newBook = new Workbook();
        //Clear the default worksheets
        newBook.getWorksheets().clear();

        //Create another temp workbook
        Workbook tempBook = new Workbook();

        //Loop through the array of Excel workbooks, copy worksheets in each Excel workbook into the new workbook
        for (String file : inputFiles)
        {
            tempBook.loadFromFile(file);
            for (Worksheet sheet : (Iterable<Worksheet>)tempBook.getWorksheets())
            {
                newBook.getWorksheets().addCopy(sheet, WorksheetCopyType.CopyAll);
            }
        }

        //Save the resultant file
        newBook.saveToFile("MergeWorkbooks.xlsx", ExcelVersion.Version2013);
    }
}

Design a site like this with WordPress.com
Get started