简体   繁体   中英

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

I struct with copy the html table to excel from web page and i tried with below code and no result coming. please suggest on this how to solve. i did all the experimental things but not getting correct result.

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();
         }
      }
}

You have multiple problems in your code,

This loop Element table : doc.select("gridMarket") Result might not come, so use doc.getElementById(<>) to fetch the info.

  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());
                 }

  }

Once you wrote the data to the sheet you have to flush it to file system something like follows and should close the workbook.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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