I have written a code to pick data for certain area in the input excel and the transpose and paste it in the output excel. This read and write are 2 separate methods, which i call from main method. However, once the code runs and the file is generated, it only shows the data written for the last write method call. As per my understanding, it has to be because, my code is creating a new workbook object every time. Though i have tried to overcome this by using static keyword in my code. Please see below for the code.
public class DataExtractor {
static FileOutputStream output = null;
static XSSFWorkbook workbook = null;
static XSSFSheet sheet = null;
static XSSFWorkbook outputWorkbook = null;
static XSSFSheet outputSheet = null;
static XSSFRow row = null;
DataFormatter dataFormatter = null;
public DataExtractor(XSSFWorkbook workbook, XSSFSheet sheet, XSSFWorkbook outputWorkbook, XSSFSheet outputSheet) {
DataExtractor.workbook = workbook;
DataExtractor.sheet = sheet;
DataExtractor.outputWorkbook = outputWorkbook;
DataExtractor.outputSheet = outputSheet;
}
private ArrayList<ArrayList<String>> fetchDataFromInputExcel(){
//code for fetching data from excel/reading excel only for some grids.
}
private ArrayList<ArrayList<String>> pasteTransposedDataIntoOutputExcel(){
//code for transposing data and pasting it into output excel/writing to excel.
}
public static void main(String args[]){
File file = new File("path of xlsx file");
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("SHEETNAME");
outputWorkbook = new XSSFWorkbook();
outputSheet = outputWorkbook.createSheet("OUTPUT");
DataExtractor obj = new DataExtractor(workbook, sheet, outputWorkbook, outputSheet);
ArrayList<ArrayList<String>> header = dataExtractor.fetchDataFromInputExcel(//args for mentioning grid area row and col are passed here);
ArrayList<ArrayList<String>> data = dataExtractor.fetchDataFromInputExcel(//args for mentioning grid area row and col are passed here);
dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, data, 1, 8);
dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, header, 1, 1);
output = new FileOutputStream(new File("path of output.xlsx file"));
outputWorkbook.write(output);
}
}
Only dataExtractor.pasteTransposedDataIntoOutputExcel(dataExtractor, header, 1, 1) operation is performed and i do not see the data for the previous one. Please suggest.
Method for transposeAndPaste:
private boolean transposeAndPasteData(DataExtractor dataExtractor, ArrayList<ArrayList<String>> data, int startRowNum, int startColNum){
XSSFCell cell = null;
XSSFRow row = null;
outputWorkbook = dataExtractor.getOutputWorkbook();
outputSheet = dataExtractor.getOutputSheet();
try {
int startRowIndex = startRowNum - 1;
int startColIndex = startColNum - 1;
//paste data row wise
//for(int rowNum = startColNum-1; rowNum<startColNum+data.size(); rowNum++) {}
Iterator<ArrayList<String>> colItr = data.iterator();
while(colItr.hasNext()) {
row = outputSheet.createRow(startRowIndex++);
ArrayList<String> colData = colItr.next();
Iterator<String> rowItr = colData.iterator();
while(rowItr.hasNext()) {
cell = row.createCell(startColIndex++);
cell.setCellValue(rowItr.next());
}
startColIndex = startColNum - 1;
}
dataExtractor.setOutputSheet(outputSheet);
return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
Thanks,
Aman
Related
There is a script to test the product listing page.
During this script, the data from the web page (in the form of two List with the name and price) should be transferred twice to the .xlsx file, each time to a new sheet.
The problem is that the xlsx file is overwritten after the second call.
The SmartsPopular sheet disappears and Smarts 3-6 K appears instead.
public class Script
#Test
public void script3() throws IOException {
openSmartphones();
moreGoodsClick();
moreGoodsClick();
FileExcelCreating.main("SmartsPopular", goodsNamesListCreating, goodsPricesListCreating);
moreGoodsClick();
moreGoodsClick();
FileExcelCreating.main("Smarts 3-6 K", goodsNamesListCreating, goodsPricesListCreating);
---------------------------------------------------------------------------------------------------------
public class FileExcelCreating
public static void main(String sheetName, List<String> goodsNames, List<String> goodsPrices) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(sheetName);
Row r0 = sheet.createRow(0);
Cell c0 = r0.createCell(0);
c0.setCellValue("Name");
Cell c1 = r0.createCell(1);
c1.setCellValue("Price");
Row a;
List<Integer> goodsPricesInt = new ArrayList<>();
for(String s : goodsPrices) goodsPricesInt.add(Integer.valueOf(s));
for (int i = 0; i < goodsNames.size(); i++) {
a = sheet.createRow(i+1);
String name = goodsNames.get(i);
a.createCell(0).setCellValue(name);
}
for (int j = 0; j < goodsPricesInt.size(); j++) {
a = sheet.getRow(j+1);
Integer price = goodsPricesInt.get(j);
a.createCell(1).setCellValue(price);
}
sheet.setAutoFilter(CellRangeAddress.valueOf("A1:B" + (goodsPricesInt.size())));
FileOutputStream outputStream = new FileOutputStream ("/FilesTXT/Smartphones.xlsx");
wb.write(outputStream);
outputStream.close();
}
The code line Workbook wb = new XSSFWorkbook(); always creates a new empty workbook. Then your code creates one sheet in it and writes that workbook having one sheet into the file. So it is pretty clear, that the result always will be a file having a workbook having one sheet in it.
You needs check whether there is already a file. If so, then create the Workbook from that file. Then you will have the partially filled workbook. Of course then you needs also check whether the sheet name already exists in the workbook because one cannot creating two sheets having the same name.
...
private static final String fileName = "./FilesTXT/Smartphones.xlsx";
...
...
Workbook wb = null;
File file = new File(fileName);
if(file.exists()) {
wb = WorkbookFactory.create(new FileInputStream(file));
} else {
wb = new XSSFWorkbook();
}
Sheet sheet = wb.getSheet(sheetName); if(sheet == null) sheet = wb.createSheet(sheetName);
...
Since there are other issues in your code in my opinion. I would not name a method main which is not really a main method in terms of Java. And there is only one loop necessary for creating the cell contents. So I will provide a complete example:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.List;
import java.util.ArrayList;
public class TestScript {
public static void main(String[] args) throws Exception {
List<String> goodsNamesListCreating = new ArrayList<String>();
goodsNamesListCreating.add("SmartsPopular Name 1");
goodsNamesListCreating.add("SmartsPopular Name 2");
goodsNamesListCreating.add("SmartsPopular Name 3");
List<String> goodsPricesListCreating = new ArrayList<String>();
goodsPricesListCreating.add("123");
goodsPricesListCreating.add("456");
goodsPricesListCreating.add("789");
FileExcelCreating.create("SmartsPopular", goodsNamesListCreating, goodsPricesListCreating);
goodsNamesListCreating = new ArrayList<String>();
goodsNamesListCreating.add("Smarts 3-6 K Name 1");
goodsNamesListCreating.add("Smarts 3-6 K Name 2");
goodsNamesListCreating.add("Smarts 3-6 K Name 3");
goodsNamesListCreating.add("Smarts 3-6 K Name 4");
goodsPricesListCreating = new ArrayList<String>();
goodsPricesListCreating.add("321");
goodsPricesListCreating.add("654");
goodsPricesListCreating.add("987");
FileExcelCreating.create("Smarts 3-6 K", goodsNamesListCreating, goodsPricesListCreating);
}
}
class FileExcelCreating {
private static final String fileName = "./FilesTXT/Smartphones.xlsx";
public static void create(String sheetName, List<String> goodsNames, List<String> goodsPrices) throws Exception {
Workbook wb = null;
File file = new File(fileName);
if(file.exists()) {
wb = WorkbookFactory.create(new FileInputStream(file));
} else {
wb = new XSSFWorkbook();
}
Sheet sheet = wb.getSheet(sheetName); if(sheet == null) sheet = wb.createSheet(sheetName);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("Price");
List<Integer> goodsPricesInt = new ArrayList<>();
for(String s : goodsPrices) goodsPricesInt.add(Integer.valueOf(s));
for (int i = 0; i < goodsNames.size(); i++) {
row = sheet.createRow(i+1);
String name = goodsNames.get(i);
row.createCell(0).setCellValue(name);
Integer price = (i < goodsPricesInt.size())?goodsPricesInt.get(i):null;
if (price != null) row.createCell(1).setCellValue(price);
}
sheet.setAutoFilter(CellRangeAddress.valueOf("A1:B" + goodsNames.size()));
FileOutputStream outputStream = new FileOutputStream(file);
wb.write(outputStream);
outputStream.close();
wb.close();
}
}
While Download xlsx using apache poi version 3.15 in ubuntu it is giving me:
java.lang.IllegalArgumentException: Attempting to write a row[1] in the range [0,1] that is already written to disk at org.apache.poi.xssf.streaming.SXSSFSheet.createRow(SXSSFSheet.java:133),
at org.apache.poi.xssf.streaming.SXSSFSheet.createRow(SXSSFSheet.java:62)
String fileName = "myDownloads"+".xlsx";
String sourceFolderPath = "/home/user/sampleFile/";
FileInputStream fileInputStream = new
FileInputStream(sourceFolderPath+"SampleFile.xlsx");
XSSFWorkbook wb_template = new XSSFWorkbook(fileInputStream);
fileInputStream.close();
String destinationFolderPath = "/home/user/downloads";
File dir = new File(destinationFolderPath);
if (!dir.exists()) {
dir.mkdirs();
}
SXSSFWorkbook workbook = new SXSSFWorkbook(wb_template);
workbook.setCompressTempFiles(true);
SXSSFSheet workSheet = (SXSSFSheet) workbook.getSheetAt(0);
workSheet.setRandomAccessWindowSize(100000);
SXSSFSheet workSheet1 = (SXSSFSheet) workbook.getSheetAt(1);
workSheet1.setRandomAccessWindowSize(100000);
List<Student> studentList = studnetDao.getStudentListByName("kumar");
if(CollectionUtils.isNotEmpty(studentList)) {
Integer rowIndex = 1;
for(Student s : studentList) {
Row row = workSheet.getRow(rowIndex);
if (row == null) {
row = workSheet.createRow(rowIndex);
}
}
}
The stream mode doesn't support overriding or accessing existing rows. you're using a template to create your workbook that write the second row automatically.
To solve this, you can use simple XSSWorkbook to load the template and remove the existing ones; then switch to stream mode.
Your code will be like this:
// -- create XSSFWorkbook from the template
XSSFWorkbook xssfworkbook = new XSSFWorkbook(wb_template);
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(1);
xssfSheet.removeRow(xssfSheet.getRow(1));
// -- after removing the first row; switch to stream mode. now we can start from index=1
SXSSFWorkbook workbook = new SXSSFWorkbook(xssfworkbook);
workbook.setCompressTempFiles(true);
SXSSFSheet workSheet = (SXSSFSheet) workbook.getSheetAt(0);
workSheet.setRandomAccessWindowSize(100000);
SXSSFSheet workSheet1 = (SXSSFSheet) workbook.getSheetAt(1);
workSheet1.setRandomAccessWindowSize(100000);
List<Student> studentList = studnetDao.getStudentListByName("kumar");
if(CollectionUtils.isNotEmpty(studentList)) {
Integer rowIndex = 1;
for(Student s : studentList) {
Row row = workSheet.getRow(rowIndex);
if (row == null) {
row = workSheet.createRow(rowIndex);
}
}
}
I have the solution to copy .xls workbook in java but not able to copy .xlsx workbook.
Anybody have solution.
I have searched google, stackoverflow and found solution only to copy xls files.
If anyone wants a simpler procedure just use Files.copy:
File originalWb = new File("orginalWb.xlsx");
File clonedWb = new File("clonedWb.xlsx");
Files.copy(originalWb.toPath(), clonedW.toPath());
No need for any bloated code
I didn't test my code. Just wrote it to give you a basic idea of what to do.
public class CopyXSSFWorkbook {
public static void main(String[] args) {
// Read xlsx file
XSSFWorkbook oldWorkbook = null;
try {
oldWorkbook = (XSSFWorkbook) WorkbookFactory.create(new File("old.xlsx"));
} catch (Exception e) {
e.printStackTrace();
return;
}
final XSSFWorkbook newWorkbook = new XSSFWorkbook();
// Copy style source
final StylesTable oldStylesSource = oldWorkbook.getStylesSource();
final StylesTable newStylesSource = newWorkbook.getStylesSource();
oldStylesSource.getFonts().forEach(font -> newStylesSource.putFont(font, true));
oldStylesSource.getFills().forEach(fill -> newStylesSource.putFill(new XSSFCellFill(fill.getCTFill())));
oldStylesSource.getBorders()
.forEach(border -> newStylesSource.putBorder(new XSSFCellBorder(border.getCTBorder())));
// Copy sheets
for (int sheetNumber = 0; sheetNumber < oldWorkbook.getNumberOfSheets(); sheetNumber++) {
final XSSFSheet oldSheet = oldWorkbook.getSheetAt(sheetNumber);
final XSSFSheet newSheet = newWorkbook.createSheet(oldSheet.getSheetName());
newSheet.setDefaultRowHeight(oldSheet.getDefaultRowHeight());
newSheet.setDefaultColumnWidth(oldSheet.getDefaultColumnWidth());
// Copy content
for (int rowNumber = oldSheet.getFirstRowNum(); rowNumber < oldSheet.getLastRowNum(); rowNumber++) {
final XSSFRow oldRow = oldSheet.getRow(rowNumber);
if (oldRow != null) {
final XSSFRow newRow = newSheet.createRow(rowNumber);
newRow.setHeight(oldRow.getHeight());
for (int columnNumber = oldRow.getFirstCellNum(); columnNumber < oldRow
.getLastCellNum(); columnNumber++) {
newSheet.setColumnWidth(columnNumber, oldSheet.getColumnWidth(columnNumber));
final XSSFCell oldCell = oldRow.getCell(columnNumber);
if (oldCell != null) {
final XSSFCell newCell = newRow.createCell(columnNumber);
// Copy value
setCellValue(newCell, getCellValue(oldCell));
// Copy style
XSSFCellStyle newCellStyle = newWorkbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
newCell.setCellStyle(newCellStyle);
}
}
}
}
}
try {
oldWorkbook.close();
newWorkbook.write(new FileOutputStream("new.xlsx"));
newWorkbook.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private static void setCellValue(final XSSFCell cell, final Object value) {
if (value instanceof Boolean) {
cell.setCellValue((boolean) value);
} else if (value instanceof Byte) {
cell.setCellValue((byte) value);
} else if (value instanceof Double) {
cell.setCellValue((double) value);
} else if (value instanceof String) {
if (value.startsWith("=")) {
// Formula String
cell.setCellFormula(value.substring(1));
} else {
cell.setCellValue(cstr);
}
} else {
throw new IllegalArgumentException();
}
}
private static Object getCellValue(final XSSFCell cell) {
switch (cell.getCellTypeEnum()) {
case BOOLEAN:
return cell.getBooleanCellValue(); // boolean
case ERROR:
return cell.getErrorCellValue(); // byte
case NUMERIC:
return cell.getNumericCellValue(); // double
case STRING:
case BLANK:
return cell.getStringCellValue(); // String
case FORMULA:
return "=" + cell.getCellFormula(); // String for formula
default:
throw new IllegalArgumentException();
}
}
}
Using Apache POI XSSF library:
public void copyFile(String sourcePath, String destinationPath) throws IOException {
FileInputStream excelFile = new FileInputStream(new File(sourcePath));
Workbook workbook = new XSSFWorkbook(excelFile);
FileOutputStream outputStream = new FileOutputStream(destinationPath);
workbook.write(outputStream);
workbook.close();
}
Clone a workbook in memory (if you can efford it):
public static Workbook cloneWorkbook(final Workbook workbook) {
try {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4096);
workbook.write(outputStream);
return WorkbookFactory.create(new ByteArrayInputStream(outputStream.toByteArray()));
} catch (final IOException ex) {
log.warn("Error cloning workbook", ex);
return null; // or throw exception
}
}
Apache POI Busy Developers' Guide to HSSF and XSSF Features
POI performs these steps on XLS/XLSX File. XLS: HSSFWorkbook, XLSX: XSSFWorkbook
Read the File as Stream (FileStream): SystemFile to JavaFileObject
Create a WorkBook form Stream. Stream to XSSFWorkbook-JavaObject
Using POI functions you can perform CURD operations on Java Workbook Object.
Convert Java Workbook Object to file/stream.
NOTE: Index Starts form 0 for Row/Column/Sheet.
Following operations are performed on Sheets:
XLSX File with Sheet1, Sheet2
getSheet_RemoveOthers(Sheet1). XLSX File:Sheet1
public static XSSFSheet getSheet_RemoveOthers(String sourceFileSheetName) {
XSSFSheet srcSheet = workBook.getSheet(sourceFileSheetName);
//Sheet srcSheet = oldWorkbook.getSheetAt(0);
int srcSheetIndex = workBook.getSheetIndex(srcSheet);
System.out.println("srcSheetIndex:"+srcSheetIndex);
int numberOfSheets = workBook.getNumberOfSheets();
for (int indexAt = 0; indexAt < numberOfSheets; indexAt++) {
if (srcSheetIndex == indexAt) {
System.out.println("sourceFileSheetName:"+indexAt);
} else {
String sheetName = workBook.getSheetName(indexAt);
System.out.println("Removing sheetName:"+sheetName);
workBook.removeSheetAt(indexAt);
}
}
System.out.println("getSheetName : "+ srcSheet.getSheetName() );
int totalRows = srcSheet.getPhysicalNumberOfRows();
System.out.println("Total Number of Rows : "+ totalRows );
return srcSheet;
}
XSSFSheet.cloneSheet(Sheet1). XLSX File:Sheet1, Sheet1 (2)
public static XSSFSheet cloneSheet(String sourceFileSheetName) {
Sheet srcSheet = workBook.getSheet(sourceFileSheetName);
int srcSheetIndex = workBook.getSheetIndex(srcSheet);
System.out.println("srcSheetIndex:"+srcSheetIndex);
XSSFSheet cloneSheet = workBook.cloneSheet(srcSheetIndex);
return cloneSheet;
}
Full-Length Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class POI_XLSX_Report {
static String filePath = "C:/Yash/",
sourceFile = filePath+"POIExcel.xlsx", sourceFileSheetName = "Sheet1",
destinationFile = filePath+"POIExcelCopy.xlsx";
static XSSFWorkbook workBook;
public static void main(String[] args) throws Exception {
File mySrcFile = new File(sourceFile);
FileInputStream stream = new FileInputStream(mySrcFile);
workBook = (XSSFWorkbook) WorkbookFactory.create( stream );
XSSFSheet sheet_RemoveOthers = getSheet_RemoveOthers(sourceFileSheetName);
setSheetValue(sheet_RemoveOthers, 4, 6, "Val2");
// New Sheet with exact copy of Source-Sheet
XSSFSheet cloneSheet = cloneSheet(sourceFileSheetName);
setSheetValue(cloneSheet, 4, 6, "Val2");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workBook.write( byteArrayOutputStream );
byteArrayOutputStream.close();
File clonedWb = new File(destinationFile);
//Files.copy(mySrcFile.toPath(), clonedWb.toPath()); If a file is already available then throws exception
// Write the output to a file
FileOutputStream fileOutputStream = new FileOutputStream( clonedWb );
byteArrayOutputStream.writeTo(fileOutputStream);
}
public static XSSFSheet getSheet_RemoveOthers(String sourceFileSheetName) {
// ...
}
public static XSSFSheet cloneSheet(String sourceFileSheetName) {
// ...
}
public static void setSheetValue(Sheet sheet, int colIndex, int rowIndex, String value) {
// Row and Column index starts form 0
rowIndex = rowIndex - 1;
colIndex = colIndex - 1;
Row row = sheet.getRow(rowIndex);
if (row == null) {
System.out.println("createRow:");
Row createRow = sheet.createRow(rowIndex);
row= createRow;
}
short lastCellNum = row.getLastCellNum();
System.out.println("Col:"+lastCellNum);
Cell createCell = row.createCell(colIndex, CellType.STRING);
System.out.println("New cell:"+createCell.getStringCellValue());
createCell.setCellValue(value);
}
}
I want to save the values from a table in excel and store them into a String[][] variable in order to make it easier to manipulate, here is my code:
public class TakingDataFromExcel {
public static void main(String[] args) {
try{
FileInputStream file = new FileInputStream(new File("C:\\Book1.xls"));
Workbook workbook = new HSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
String[][] headers= null;
String value = null;
for (int i= 0;i < sheet.getPhysicalNumberOfRows(); i++) {
DataFormatter formatter = new DataFormatter();
for (int j=0; j<=6;j++) {
Row row = sheet.getRow(i);
value = formatter.formatCellValue(row.getCell(j));
headers[i][j].concat(value.toString());
}
}
System.out.println(headers);
System.out.println(sheet.getPhysicalNumberOfRows());
String[] cdsid=null;
cdsid=headers[1][1].split(" ");
for (int x=0; x<cdsid.length;x++) {
System.out.println(cdsid[x]);
}
file.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
I'm still getting a null pointer exception error but I canĀ“t see where it is. I am open to any suggestions if you think there is is an easier way to do this task.
And here is the error:
java.lang.NullPointerException
at com.ford.samples.TakingDataFromExcel.main(TakingDataFromExcel.java:26)
You never initialize your 2 dimensional String[] .
String[][] headers= null; should be
String[][] headers= new String[SOME_X][SOME_Y]
getPhysicalNumberOfRows() will just count the number of rows in the sheet that are defined. You are iterating over rows assuming that they are sequential. Is it possible that you have an empty row in your spreadsheet and getRow(j) is returning null?
You can try something like this:
Iterator<Row> rowIt = sheet.rowIterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
}
I am reading data from an arraylist and writing this to an excel sheet. The problem is my excel is getting overwritten each time. Here is my code. I can't figure out what is wrong here :( Can someone please help?
public static void main( String[] args ) throws Exception
{
List<String> fileData = new ArrayList<String>();
for(File file:files) {
fileData.add(readFileContents(file.getAbsolutePath()));
}
for(String fileContent:fileData) {
//do some stuff that in turn calls the writeDataToExcel method
}
}
private static void writeDataToExcel(String test,Map<String,String> dataMap,Object object) throws IOException {
File file = new File("input/data.xls");
Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();
XSSFWorkbook workbook = null;
int count = 0;
XSSFSheet sheet = null;
if(file.exists()) {
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("Data Sheet");
}
else {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data Sheet");
//count = sheet.getLastRowNum();
}
data.put("1", new Object[]{"Id","Name","Field","Description","Value"});
for(Map.Entry<String, String> dataMp:dataMap.entrySet()) {
data.put(Integer.toString(count+2), new Object[]{id,object.getClass().getSimpleName(),dataMp.getKey(),dataMp.getValue(),"null"});
count++;
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
}
}
FileOutputStream fis = new FileOutputStream("input/data.xls");
workbook.write(fis);
if(fis!=null)
fis.close();
}
I think problem is at line
int rownum = 0;
this will set rowNUm to zero each time and sheet will be written from zero row
You need to persist this rowNum value if you want to append data in the sheet