When operating an Excel table that contains a large amount of data, blank rows and columns may remain due to changes in the data. At that time, Free Spire.XLS for Java can solve it. Through this library, you can delete blank rows and columns in Excel worksheets at once. Now, I will share the Java code related to the countermeasure with you.
** Import JAR package ** ** Method 1: ** Download Free Spire.XLS for Java, unzip it, and then in the lib folder Import the Spire.Xls.jar package as a dependency into your Java application.
** Method 2: ** After installing the JAR package directly from the Maven repository, configure the pom.xml file as follows:
<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.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>
** The original Excel document is: **
** Java code **
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class DeleteBlankRowsAndColumns {
public static void main(String[] args) {
//Import an Excel document
Workbook wb = new Workbook();
wb.loadFromFile("sample1.xlsx ");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Loop all lines
for (int i = sheet.getLastRow(); i >= 1; i--)
{
//Determine if it is a blank line
if (sheet.getRows()[i-1].isBlank())
{
//Deletes the specified line
sheet.deleteRow(i);
}
}
//Loop through all columns
for (int j = sheet.getLastColumn(); j >= 1; j--)
{
//Check if it is a blank column
if (sheet.getColumns()[j-1].isBlank())
{
//Deletes the specified column
sheet.deleteColumn(j);
}
}
//Save the document
wb.saveToFile("deleteBlank.xlsx", ExcelVersion.Version2016);
}
}
Execution result:
Recommended Posts