I want to insert new rows while writing in Excel sheet.
Here is my code:
public static void addValuesInWorkbook(String pathAndFileName, String sheetName,
int rowNum, String valuesString,String delimeter) {
if(pathAndFileName.length() > 0 && sheetName.length() > 0 && rowNum >= 0 && valuesString.length() > 0 && delimeter.length() > 0)
{
String[] colValues= null;
if("|".equals(delimeter))
colValues = valuesString.split("\\|");
else
colValues = valuesString.split(delimeter);
int cellnum = 0;
FileInputStream fsIP;
try {
fsIP = new FileInputStream(new File(pathAndFileName));
//Read the spreadsheet that needs to be updated
if(rowNum > 0)
{
rowNum--; //As row indexing starts from 0
}
HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook
HSSFSheet sheet = wb.getSheet(sheetName);
HSSFRow row = sheet.getRow(((rowNum>0)?rowNum:0));
HSSFCell cell=null;
for(String colValue:colValues)
{ if(row!=null){
cell = row.getCell(cellnum);
if(cell==null)
cell = row.createCell(cellnum);
}
else if (row == null)
{
row =sheet.createRow(rowNum); //Create a row if it does not exist
cell = row.createCell(cellnum);
}
cell.setCellValue(colValue);
cellnum++;
}
fsIP.close(); //Close the InputStream
FileOutputStream output_file =new FileOutputStream(new File(pathAndFileName)); //Open FileOutputStream to write updates
wb.write(output_file); //write changes
output_file.close(); //close the stream
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Values are getting inserted with headers(column names ) but whenever new rows are inserted it replaces the older row values.
Please help.