gpt4 book ai didi

java - 使用 JAVA 中的 JSOUP 和 Apache POI 将 HTML 表转换为 Excel

转载 作者:行者123 更新时间:2023-12-02 11:06:25 24 4
gpt4 key购买 nike

我通过将 html 表从网页复制到 excel 来进行构造,我尝试使用下面的代码,但没有结果。请建议如何解决这个问题。我做了所有的实验,但没有得到正确的结果。

package javaautomation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class test {

public static void main(String[] args)
{


try {
Document doc = Jsoup.connect("https://www.ftrac.co.in/CP_SEC_MEM_MARK_WATC_VIEW.aspx").get();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");

for (Element table : doc.select("gridMarket")) {
int rownum = 0;
for (Element row : table.select("tr")) {
HSSFRow exlrow = sheet.createRow(rownum++);
int cellnum = 0;
for (Element tds : row.select("td")) {
StringUtils.isNumeric("");
HSSFCell cell = exlrow.createCell(cellnum++);
cell.setCellValue(tds.text());
}
}
}


}catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

您的代码中有多个问题,

此循环元素表:doc.select("gridMarket")结果可能不会出现,因此请使用doc.getElementById(<>)来获取信息。

  Element table = doc.getElementById(<<Id of table>>);
if(table != null) {

int rownum = 0;
for (Element row : table.select("tr")) {
HSSFRow exlrow = sheet.createRow(rownum++);
int cellnum = 0;
for (Element tds : row.select("td")) {
StringUtils.isNumeric("");
HSSFCell cell = exlrow.createCell(cellnum++);
cell.setCellValue(tds.text());
}

}

将数据写入工作表后,您必须将其刷新到文件系统,如下所示,并且应该关闭工作簿。

        File file = new File("Report" + new Date().getTime() + ".xlsx");

System.out.println(file.getAbsolutePath());
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
workbook.close();

关于java - 使用 JAVA 中的 JSOUP 和 Apache POI 将 HTML 表转换为 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com