繁体   English   中英

在JAVA中使用JSOUP和Apache POI将HTML表转换为Excel

[英]HTML Table Convert Into Excel using of JSOUP & Apache POI in JAVA

我通过从网页复制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();
         }
      }
}

您的代码中有多个问题,

此循环Element table : 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();

暂无
暂无

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

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