Search code examples
javaexcelxssf

When i Try to write row and column in an excel sheet using a loop only the last loop values gets print


I want to print all the rows and column in my excel, but it always print the last column alone(i.e. whatever writes in the last loop).

Is there a way to get print all the values and not overwrite the excel again and again. below is the program i used please let me know where i have mistaken.

I want the 1st Column get printed first and then the 2nd column. Don't want the row to get print first


public class test {

    public static void main(String[] args) throws IOException, Exception  {
        XSSFWorkbook wb=new XSSFWorkbook();
        XSSFSheet spreadsheet=wb.createSheet();
        FileOutputStream fos=null;

        for(int j=0; j<4; j++) {
            for(int i=0; i<10; i++) {
                Row row=spreadsheet.createRow(i);
                Cell value=row.createCell(j);
                value.setCellValue(i+" Test");
                fos=new FileOutputStream("Testexcel.xlsx");
                wb.write(fos);
            }
        }

        wb.close();
        fos.close();
    }
}

This is the result I got

This is the result I got

This is the result I want

This is the result I want


Solution

  • please try this code

    public class test {
    
        public static void main(String[] args) throws IOException, Exception  {
            XSSFWorkbook wb=new XSSFWorkbook();
            XSSFSheet spreadsheet=wb.createSheet();
            FileOutputStream fos=null;
            for(int i=0; i<10; i++) {
                Row row=spreadsheet.createRow(i);
                for(int j=0; j<4; j++) {
                    Cell value=row.createCell(j);
                    value.setCellValue(i+" Test");
                    
                }
            }
           fos=new FileOutputStream("Testexcel.xlsx");
           wb.write(fos);
    
            wb.close();
            fos.close();
        }
    }
    

    ok for you case try this and get back to me i cant test this. cause i don't have the source code.

    public class test {
    
    public static void main(String[] args) throws IOException, Exception  {
        XSSFWorkbook wb=new XSSFWorkbook();
        XSSFSheet spreadsheet=wb.createSheet();
        FileOutputStream fos=null;
        for(int i=0; i<10; i++) {
            Row row=spreadsheet.createRow(i);
        }
        for(int j=0; j<4; j++) {
             for(int i=0; i<10;i++){
               Row row = spreadsheet.getRow(i);
                Cell value=row.createCell(j);
                value.setCellValue(i+" Test");
                }
            }
       fos=new FileOutputStream("Testexcel.xlsx");
       wb.write(fos);
    
        wb.close();
        fos.close();
     }
    }