How to use Java to delete blank rows and columns in Excel

When we are operating some Excel tables containing a large amount of data, some blank rows or columns may be left due to the modification of the data. At this time, we can use Free Spire.XLS for Java to delete the blank rows and columns in the Excel worksheet in batches. Blank column, and then I will share the Java code used.

The original Excel document is as follows:

Product installation:

1. Download the Free Spire.XLS for Java package and unzip it, then import the Spire.Xls.jar package in the lib folder as a dependency into the Java application.

2. Install the JAR package directly through the Maven repository, and configure the pom.xml file as follows:

当我们在操作一些包含大量数据的Excel表格时,可能会因为修改数据而留下一些空白行或列,此时我们可以借助Free Spire.XLS for Java来批量删除Excel工作表中存在的空白行和空白列,接下来就将使用到的Java代码分享给大家。

 

Excel原文档如下:



 

产品安装:

1. 下载Free Spire.XLS for Java包并解压缩,然后将lib文件夹下的Spire.Xls.jar包作为依赖项导入到Java应用程序中。

2. 直接通过Maven仓库安装JAR包,按如下所示配置pom.xml文件:

Product installation:

1. Download the Free Spire.XLS for Java package and unzip it, then import the Spire.Xls.jar package in the lib folder as a dependency into the Java application.

2. Install the JAR package directly through the Maven repository, and configure the pom.xml file as follows:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>2.2.0</version>
    </dependency>
</dependencies>

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) {

        //加载测试文档
        Workbook wb = new Workbook();
        wb.loadFromFile("test2.xlsx ");

        //获取第一个工作表
        Worksheet sheet = wb.getWorksheets().get(0);

        //遍历所有行
        for (int i = sheet.getLastRow(); i >= 1; i--)
        {
            //判断行是否空白
            if (sheet.getRows()[i-1].isBlank())
            {
                //删除指定行
                sheet.deleteRow(i);
            }
        }

        //遍历所有列
        for (int j = sheet.getLastColumn(); j >= 1; j--)
        {
            //判断列是否空白
            if (sheet.getColumns()[j-1].isBlank())
            {
                //删除指定列
                sheet.deleteColumn(j);
            }
        }

        //保存文档
        wb.saveToFile("DeleteBlankRowsAndColumns.xlsx", ExcelVersion.Version2016);
    }
}

Result document :

Guess you like

Origin blog.csdn.net/zx309519477/article/details/108755825