Delete data in Excel using Java

Deleting data from an Excel file using Java requires a similar approach as updating data. Since Excel files are not typically considered as databases, there is no direct “delete” operation. Instead, you need to read the file, identify the data you want to delete, remove it, and then write the modified data back to the file.

Here’s an example code snippet that demonstrates how to delete data from an Excel file using Java and the Apache POI library:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDataDeleter {
    public static void main(String[] args) {
        String filePath = "/path/to/your/excel_file.xlsx";
        String sheetName = "Sheet1";
        int rowToDelete = 1;

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheet(sheetName);
            Row row = sheet.getRow(rowToDelete);

            if (row != null) {
                sheet.removeRow(row);

                try (FileOutputStream fos = new FileOutputStream(filePath)) {
                    workbook.write(fos);
                    System.out.println("Excel file updated successfully.");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("Row does not exist.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Replace /path/to/your/excel_file.xlsx with the actual path to the Excel file you want to delete data from. In this example, we are deleting row 1 (2nd row) from the sheet.

This code uses the Apache POI library to read the Excel file, retrieve the specified sheet, and get the row to delete. If the row exists, it is removed from the sheet. Finally, the modified workbook is saved back to the Excel file.

Make sure to include the Apache POI library (poi-.jar, poi-ooxml-.jar) in your classpath. You can download the library from the Apache POI website or include it as a Maven/Gradle dependency

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech