简体   繁体   中英

Unable to write to an excel (Selenium WebDriver) - Apache POI

I am new to Selenium Web automation please be soft on me.

I have created a method to write an array content to an excel sheet. I get no exception or error and I don't see data being written to excel sheet.

Name of excel sheet-mysheet.xlsx Name of sheet within excel workbook:"FirstLevelMenu"

public class WriteExcelData {
    XSSFWorkbook wb;
    XSSFSheet sheet;

    public void writeData(String path, String sheetName, String[] data) {

        try {
            File src = new File(path);
            FileInputStream fis = new FileInputStream(src);
            wb = new XSSFWorkbook(fis);
            sheet = wb.getSheet(sheetName);
            int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
            Row row = sheet.getRow(0);
            Row newRow = sheet.createRow(rowCount + 1);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell col = newRow.createCell(j);
                col.setCellValue(data[j]);
            }
            fis.close();
            FileOutputStream fout = new FileOutputStream(src);
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public static void main(String[] args) {
        WriteExcelData test=new WriteExcelData();
        String[] data=new String[2];
        data[0]="cat";
        data[1]="cat";

        test.writeData("C:\\mysheet.xlsx", "FirstLevelMenu", data);
    }
}

As you are using a fresh xlsx sheet to write, please try below code...I am sure it will work :)

public static void main(String[] args) throws InvalidFormatException, IOException{

    FileInputStream fis=new FileInputStream("D://Data.xlsx");
    XSSFWorkbook wb= new XSSFWorkbook(fis);

    //XSSFSheet sh= wb.getSheetAt(0); Or
    XSSFSheet sh = wb.createSheet("Test");
    XSSFRow row=sh.createRow(0);
    XSSFCell cell= row.createCell(0);

    //cell.setCellType(cell.CELL_TYPE_STRING);
    cell.setCellValue("Ish Mishra");

    FileOutputStream fos=new FileOutputStream("D:\\Data.xlsx");
    wb.write(fos);
    fos.close();

    System.out.println("Excel File Written successfully");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM