簡體   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