【问题标题】:Trying to write data from a website to an Excel spreadsheet尝试将数据从网站写入 Excel 电子表格
【发布时间】:2021-06-28 17:09:00
【问题描述】:

我正在尝试使用 selenium 从网站获取字符串并将该字符串写入 Excel 文档。

        File file= new File("Q:\\A_Parts routing\\03_Systeme\\Selenium\\Vega Automatisierung Teil 1\\AutomatisierterSteuerungsantrag.xls"); 
        FileInputStream fis = new FileInputStream(file);
        //int j=1; j++;
        //Access the workbook
        HSSFWorkbook wb = new HSSFWorkbook(fis);
        //Access the worksheet, so that we can update / modify it.
        HSSFSheet sheet = wb.getSheetAt(0);
        // declare a Cell object
        //HSSFCell cell = null; 
        //cell = sheet.getRow(1).getCell(11);
        System.out.println("VKEY "+VKEYVariable+ " is written in Excelsheet");
        // Access the 5. cell in second row to update the value
        //for (int r=1; r < sheet.getPhysicalNumberOfRows(); r++)
        try {
            HSSFRow row = sheet.getRow(i+1);
            if(row == null) {
                row = sheet.createRow(i+1);
            }
            Cell cell = (Cell) row.getCell(5);
            if (cell == null) {
                cell = (Cell) row.createCell(5);
            }
            ((HSSFCell) cell).setCellValue(IterateToEAMethods.VKEYVariable);
        } catch (Exception e) {
            System.out.println(e);
        }
        //Open FileOutputStream to write updates
        FileOutputStream fos =new FileOutputStream(file);
        //write changes
        wb.write(fos);
        

我在控制台中打印出一条错误消息,但我在 Google 上找不到任何表明存在问题的信息。

java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFCell cannot be cast to jxl.Cell

【问题讨论】:

  • 嗯,信息真的很清楚。你有一个类的实例,你试图把它转换成它不是的东西。告诉鸡蛋“你现在是一条鱼”也行不通。所以,问问自己为什么要写下那个演员表。它的目的是什么?为什么你认为你要投射的对象是那个特定的类?
  • 您能否分享您的 pom.xml 或构建 .gradle 并向我展示依赖关系,尤其是在您依赖 JExcel 接口 API 的地方

标签: java excel selenium


【解决方案1】:

例外情况是因为 HSSFCell 类及其父类没有扩展 Cell,所以无法转换为 Cell。我可以通过快速浏览HSSFCell javadocs 来确认这一点。在页面顶部的 java.lang.Object 下,列出了超类的层次结构,直到您到达 HSSFCell。 jxl.Cell 没有出现在该层次结构中。

查看javadocs for HSSFRow HSSFRow.getCell()HSSFRow.createCell() 都返回HSSFCell 的对象类型。

如果您将cell 声明为HSSFCell 对象并删除类型转换,您应该能够调用HSSFCell.setCellValue(java.lang.String) 方法并传入您的字符串。

HSSFCell cell = row.getCell(5);
if (cell == null) {
    cell = row.createCell(5);
}
cell.setCellValue(IterateToEAMethods.VKEYVariable);

【讨论】:

    【解决方案2】:

    您能否分享您的 pom.xml 或构建 .gradle 并向我展示依赖关系,尤其是在您依赖 JExcel 接口 API 的地方。您可能有旧的或不兼容的 Jexcel API 直接或间接依赖项。在您的外部 Jar 文件中检查 Jxl 版本并使用更高版本。 Jxl 看起来像这样

    <dependency>
    <groupId>jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.4.2</version>
    </dependency>
    

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 2021-04-05
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多