right now whenever i call this function the value in B3 cell of excel file workbook.xls is updated. i need to change this function such that whenever i call this function , new excel file should not be created but cell values should be appended in the order A1 on first call , A2 on 2nd call, A3 on 3rd call and so on . Can you help me with this.
private static void readFromFile(String filename) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
//Construct the BufferedReader object
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//Process the data, here we just print it out
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(2);
int s_row=1;
row.createCell(s_row).setCellValue(line);
s_row++;
// row.createCell(1).setCellValue(new Date());
FileOutputStream fileOut = new FileOutputStream("c:\\workbook.xls");
wb.write(fileOut);
fileOut.close();
// System.out.println(line);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Best Answer
Please see below for fully functioning (if a bit clumsy) implementation of what you request above. In particular, please note: (1) while loop only creates and populates cells; (2) initialization of HSSFWorkbook, Sheet, Row, and s_row occur outside the while loop; (3) file is written to disk once, at the end; (4) cells begin with index 0 instead of index 1; (5) you need to specify CreateRow(0) to get the first row in the spreadsheet; and (6) I used Sheet and Row instead...your mileage may vary! :)
Happy coding:
My testinput.txt file contained the following data:
After running the above Java code, the Microsoft Excel worksheet contained the data in the file in cells A1 through G1.