Excel files are not typically considered as databases that support direct data updates like relational databases. Instead, they are usually used for storing and presenting data. If you want to update specific data in an Excel file programmatically, you will typically need to read the file, modify the data, and then write the modified data back to the file.
Here’s an example code snippet that demonstrates how to update data in 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 ExcelDataUpdater { public static void main(String[] args) { String filePath = "/path/to/your/excel_file.xlsx"; String sheetName = "Sheet1"; int rowToUpdate = 1; int cellToUpdate = 1; String newValue = "[email protected]"; try (FileInputStream fis = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fis)) { Sheet sheet = workbook.getSheet(sheetName); Row row = sheet.getRow(rowToUpdate); if (row != null) { Cell cell = row.getCell(cellToUpdate, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); cell.setCellValue(newValue); 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 update. In this example, we are updating the value in row 1, cell 1 (B2) with the new email value “[email protected]“.
This code uses the Apache POI library to read the Excel file, retrieve the specified sheet, and get the row and cell to update. If the row exists, the cell value is updated with the new value. 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.