简体   繁体   English

无法写入Excel(Selenium WebDriver)-Apache POI

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

I am new to Selenium Web automation please be soft on me. 我是Selenium Web自动化的新手,请对我保持警惕。

I have created a method to write an array content to an excel sheet. 我创建了一种将数组内容写入Excel工作表的方法。 I get no exception or error and I don't see data being written to excel sheet. 我没有异常或错误,也看不到数据被写入excel工作表。

Name of excel sheet-mysheet.xlsx Name of sheet within excel workbook:"FirstLevelMenu" excel sheet-mysheet.xlsx的名称excel工作簿中的图纸名称:“ 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 :) 当您使用新的xlsx工作表进行书写时,请尝试以下代码...我确定它会起作用:)

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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