簡體   English   中英

嘗試將數據從網站寫入 Excel 電子表格

[英]Trying to write data from a website to an Excel spreadsheet

我正在嘗試使用 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 或 build.gradle 並向我展示依賴關系,尤其是在你依賴 JExcel 接口 API 的地方。 您可能有較舊或不兼容的 Jexcel API 直接或間接依賴項。 在您的外部 Jar 文件中檢查 Jxl 版本並使用更高版本。 Jxl 看起來像這樣

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

例外情況是,由於 HSSFCell class 及其父級不擴展Cell Cell 我可以通過快速瀏覽一下HSSFCell javadocs來確認這一點。 在頁面頂部的 java.lang.Object 下,列出了超類的層次結構,直到您進入 HSSFCell。 jxl.Cell 不會出現在該層次結構中。

查看 HSSFRow HSSFRow.getCell()HSSFRow.createCell()的 javadocs 都返回 object 類型的HSSFCell

如果您將cell聲明為HSSFCell object 並刪除類型轉換,您應該能夠調用HSSFCell.setCellValue(java.lang.String)方法並傳入您的字符串。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM