8

I have a situation where I will be reading multiple lines and after some logic I need to write the lines in an Excel Sheet. I am using Apache POI for this purpose. However, the problem that I am facing is that, only the last line (from the loop) is being written to the Excel

Can someone please help me on this or provide some code snippet?

Thanks

skaffman
  • 398,947
  • 96
  • 818
  • 769
Nathan
  • 115
  • 2
  • 4
  • 6

1 Answers1

17
    Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(2);
    cell.setCellValue("Use \n with word wrap on to create a new line");

    //to enable newlines you need set a cell styles with wrap=true
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);

    //increase row height to accomodate two lines of text
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));

    //adjust column width to fit the content
    sheet.autoSizeColumn((short)2);

    FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
    wb.write(fileOut);
    fileOut.close();
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Thanks Jigar. But What I am looking at is where I can write multiple lines to One Excel Sheet. – Nathan Feb 11 '11 at 10:43
  • FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx",true); wb.write(fileOut); fileOut.close(); – Nathan Feb 11 '11 at 10:44
  • I need to keep appending lines to an Excel Sheet. Like Open a sheet , write a line ... and again fetch another line from a loop and write that line in next row... – Nathan Feb 11 '11 at 12:16
  • I haven't practically came across the thing you are at , but have a look at http://stackoverflow.com/questions/521274/edit-existing-excel-files-using-jxl-api-apache-poi – jmj Feb 11 '11 at 14:36
  • The problem with increasing the row height like this is that your rows will skip numbers. – theblang Nov 14 '12 at 20:03