Requirement -Programatically update an Excel spreadsheet in Java.
Solutions – Here an example of Apache POI to update a XLS workbook. Apache POI is a very good API , that can be handy in manipulating Excel documents.This tutorial focuses on XLS documents (Office 97 – 2003).
The existing excel file like below –
Below is code to update the excel file import java.io.*; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.*; import java.util.Iterator; public class updateExcels { public static void main(String[] args) throws Exception{ FileInputStream fsIP= new FileInputStream(new File("C:\\TechartifactExcel.xls")); //Read the spreadsheet that needs to be updated HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook HSSFSheet worksheet = wb.getSheetAt(0); //Access the worksheet, so that we can update / modify it. Cell cell = null; // declare a Cell object cell = worksheet.getRow(2).getCell(2); // Access the second cell in second row to update the value cell.setCellValue("OverRide Last Name"); // Get current cell value value and overwrite the value fsIP.close(); //Close the InputStream FileOutputStream output_file =new FileOutputStream(new File("C:\\TechartifactExcel.xls")); //Open FileOutputStream to write updates wb.write(output_file); //write changes output_file.close(); //close the stream } }
after updating excel file would look like below –
happy coding with Vinay in techartifact ….