Java 从internet保存excel文件

Java 从internet保存excel文件,java,excel,encoding,selenium,utf-8,Java,Excel,Encoding,Selenium,Utf 8,我正在尝试使用Selenium从站点下载Excel文件 我的做法是: WebElement excelList = driver.findElement(By.xpath("...")); excelList.click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); String pageSource = driver.getPageSource(); File

我正在尝试使用Selenium从站点下载Excel文件

我的做法是:

    WebElement excelList = driver.findElement(By.xpath("..."));

    excelList.click();

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    String pageSource = driver.getPageSource();
    FileOutputStream fos = new FileOutputStream("d:/load.xls");

    for (int i = 0; i < pageSource.length(); i++) {
        char c = pageSource.charAt(i);


        fos.write((byte) c);
    }

    fos.close();
WebElement excelList=driver.findElement(By.xpath(“…”);
excelList.click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
字符串pageSource=driver.getPageSource();
FileOutputStream fos=新的FileOutputStream(“d:/load.xls”);
对于(int i=0;i
页面源字符串长度等于我从该站点手动下载的文件大小

问题是我保存的数据不正确,MS Excel无法打开保存的文件


如何正确保存文件?

您可以尝试使用
String.getBytes()
将字符重新编码回字节流,但这可能仍然不起作用

基本上,为了将excel文件的二进制数据保存在字符串中,必须使用字符集对数据进行解码。由于excel文件不应以纯文本形式读取,因此可能有许多字节序列不是有效的字符编码。当解码为
字符串时,这些字节序列可能仅表示为“?”(尽管这取决于实际使用的
字符集)。当您尝试使用
String.getBytes()
或任何其他方法重新编码字符时,这些“?”字符不会转换回其原始字节,而是会转换为unicode问号字符的编码,这几乎肯定对excel文件格式无效

真正的问题是,为什么需要通过Se下载此文件?Se是关于测试浏览器如何呈现网页的。如果您需要Excel文件,为什么不直接从正在使用Se单击的链接中获取href,然后使用一个简单的
HttpUrlConnection
使用标准二进制文件
InputStream

下载该文件呢

我所需要的只是在点击加载文件按钮后从最后一页获取正确的输入流。 但获取页面对象“lastPage()”的方法具有受保护的访问权限

方法如下:

 private static void saveExcelFile(HtmlUnitDriver driver)  {
    Method m = driver.getClass().getDeclaredMethod("lastPage", null);
    m.setAccessible(true);
    Object obj = m.invoke(driver, null);

    Page page = (Page) obj;

    InputStream stream = page.getWebResponse().getContentAsStream();

    FileOutputStream fos = new FileOutputStream("d:/load.xls");

    int c;

    while ((c = stream.read()) != -1) {
        fos.write(c);
    }

    fos.close();
}

excel文件是通过执行java脚本生成的,我只是不知道最终url的精确链接。我正在开发的解决方案旨在访问站点并收集数据,有时还用于下载文件。以Selenuim允许的方式获取数据似乎更容易