Use jsoup to parse the HTML, normalize every table into a rectangular row-and-column model, then serialize that model with Jackson (JSON), a standards-aware CSV writer, and Apache POI (XLSX). Normalizing once is the key: the same handling for headers, missing cells, rowspan, and colspan can feed all three formats.
What the conversion pipeline should do
A reliable converter has four stages:
- Load HTML from a string, file, or URL with jsoup.
- Select one or more
tableelements and traverse their logical rows inthead,tbody, andtfootorder. - Normalize spans and missing cells into a rectangular matrix with a defined column order.
- Serialize that matrix as JSON, CSV, or XLSX.
Do not write three independent parsers. A single intermediate model prevents differences such as JSON containing six columns while CSV contains five.
Dependencies and project setup
For Maven, add jsoup, Jackson, and Apache POI’s XLSX artifact:
<dependencies>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.4.1</version>
</dependency>
</dependencies>
The jsoup project currently shows 1.23.2 in its Maven and Gradle examples; check the project before pinning a version because dependencies change. Apache POI’s poi-ooxml component supplies XLSX support.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
A complete Java converter
The following Java 17 example reads a local HTML file, converts the first table (or a CSS-selected table), and writes JSON, CSV, and XLSX. It treats visible text as the cell value and collapses runs of whitespace.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class HtmlTableConverter {
record Grid(List<String> headers, List<List<String>> rows, boolean objectJson) {}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: java HtmlTableConverter input.html output-prefix [css-selector]");
System.exit(2);
}
Document doc = Jsoup.parse(Files.readString(Path.of(args[0]), StandardCharsets.UTF_8));
String selector = args.length > 2 ? args[2] : "table";
Elements tables = doc.select(selector);
if (tables.isEmpty()) throw new IllegalArgumentException("No table matched: " + selector);
Grid grid = normalize(tables.first());
ObjectMapper mapper = new ObjectMapper();
List<Object> json = new ArrayList<>();
if (grid.objectJson()) {
for (List<String> row : grid.rows()) {
Map<String,String> item = new LinkedHashMap<>();
for (int i = 0; i < grid.headers().size(); i++)
item.put(grid.headers().get(i), i < row.size() ? row.get(i) : "");
json.add(item);
}
} else {
json.addAll(grid.rows());
}
mapper.writerWithDefaultPrettyPrinter().writeValue(Path.of(args[1] + ".json").toFile(), json);
writeCsv(grid, Path.of(args[1] + ".csv"));
writeXlsx(grid, Path.of(args[1] + ".xlsx"));
}
static Grid normalize(Element table) {
Elements rows = table.select("> thead > tr, > tbody > tr, > tfoot > tr");
if (rows.isEmpty()) rows = table.select("> tr");
List<List<String>> matrix = new ArrayList<>();
for (int r = 0; r < rows.size(); r++) {
while (matrix.size() <= r) matrix.add(new ArrayList<>());
int col = 0;
for (Element cell : rows.get(r).select("> th, > td")) {
while (col < matrix.get(r).size() && matrix.get(r).get(col) != null) col++;
int colspan = Math.max(1, parseSpan(cell.attr("colspan")));
int rowspan = Math.max(1, parseSpan(cell.attr("rowspan")));
String value = cell.text().replaceAll("\s+", " ").trim();
for (int rr = r; rr < r + rowspan; rr++) {
while (matrix.size() <= rr) matrix.add(new ArrayList<>());
while (matrix.get(rr).size() < col + colspan) matrix.get(rr).add(null);
for (int cc = col; cc < col + colspan; cc++)
if (matrix.get(rr).get(cc) == null) matrix.get(rr).set(cc, value);
}
col += colspan;
}
}
int width = matrix.stream().mapToInt(List::size).max().orElse(0);
for (List<String> row : matrix) while (row.size() < width) row.add("");
if (matrix.isEmpty()) return new Grid(List.of(), List.of(), false);
List<String> candidate = matrix.get(0).stream().map(v -> v == null ? "" : v).toList();
Set<String> unique = new LinkedHashSet<>(candidate);
boolean headersOk = candidate.stream().allMatch(s -> !s.isBlank()) && unique.size() == candidate.size();
if (headersOk) return new Grid(candidate, new ArrayList<>(matrix.subList(1, matrix.size())), true);
return new Grid(List.of(), matrix, false);
}
static int parseSpan(String s) { try { return Integer.parseInt(s); } catch (Exception e) { return 1; } }
static void writeCsv(Grid grid, Path file) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
if (grid.objectJson()) writeCsvRow(out, grid.headers());
for (List<String> row : grid.rows()) writeCsvRow(out, row);
}
}
static void writeCsvRow(Writer out, List<String> row) throws IOException {
for (int i = 0; i < row.size(); i++) {
if (i > 0) out.write(',');
String v = row.get(i) == null ? "" : row.get(i);
if (v.indexOf(',') >= 0 || v.indexOf('"') >= 0 || v.indexOf('n') >= 0 || v.indexOf('r') >= 0)
out.write('"' + v.replace(""", """") + '"');
else out.write(v);
}
out.write(System.lineSeparator());
}
static void writeXlsx(Grid grid, Path file) throws IOException {
try (Workbook wb = new XSSFWorkbook(); OutputStream out = Files.newOutputStream(file)) {
Sheet sheet = wb.createSheet("Table");
int r = 0;
if (grid.objectJson()) writeSheetRow(sheet.createRow(r++), grid.headers());
for (List<String> row : grid.rows()) writeSheetRow(sheet.createRow(r++), row);
wb.write(out);
}
}
static void writeSheetRow(Row xrow, List<String> values) {
for (int c = 0; c < values.size(); c++) xrow.createCell(c, CellType.STRING).setCellValue(values.get(c) == null ? "" : values.get(c));
}
}
Compile and run it with java HtmlTableConverter page.html export '#orders'. The selector is optional; without it, the first table is used. For a URL, replace Jsoup.parse(Files.readString(...)) with Jsoup.connect(url).get() and set an appropriate timeout.
How headers and JSON shape are decided
Object arrays when headers are trustworthy
If the first meaningful row has non-empty, unique labels, the converter emits an array of objects:
[{"name":"Ada","score":"10"}]
Values remain strings. This preserves IDs, leading zeroes, and long numeric-looking values. Convert to numbers or dates only when your application has explicit, validated rules.
Array-of-arrays for ambiguous tables
When headers are absent, duplicated, or structurally ambiguous, emit rows as arrays and preserve source column order:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
[["Ada","10"],["Lin","09"]]
That is safer than inventing keys that imply meaning the HTML does not establish. If your API requires object keys, generate stable names such as column_1 and document that policy.
CSV details that prevent broken exports
- Write UTF-8 deliberately, as the example does.
- Quote fields containing commas, quotes, or line breaks.
- Escape an embedded quote by doubling it.
- Decide whether your contract always emits a final line ending; the example does.
- If untrusted values will be opened in spreadsheet software, define a CSV-injection policy for values beginning with
=,+,-, or@(for example, prefixing an apostrophe).
For production pipelines, a standards-aware CSV library can replace the small writer while retaining the same normalized model.
XLSX output and large tables
XSSFWorkbook is straightforward for ordinary workbook sizes and writes modern XLSX files through poi-ooxml. The example creates text cells intentionally, so leading zeroes and identifiers are not silently changed. Add numeric or date cell types only after defining conversion and validation rules.
Recommended Free Tools
For very large exports, use Apache POI’s SXSSFWorkbook, which streams rows with a bounded memory footprint. Dispose of its temporary files after writing, and set a row window appropriate to your workload. Do not assume that streaming removes all costs: styles, very wide tables, and shared strings still affect memory and file size.
Handling real-world HTML
Multiple tables
Expose a CSS selector such as #orders or table.data. You can call normalize for every match and write each result to a separate JSON/CSV file or a separate XLSX sheet. Do not silently merge unrelated tables.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Row and column spans
The sample expands each rowspan and colspan into a rectangular grid by repeating the cell’s visible text. If your meaning requires blank cells instead, change that policy explicitly; either choice is preferable to accidental column shifts.
Sections, empty cells, and malformed markup
Rows are read from thead, then tbody, then tfoot. Missing cells are filled with empty strings. An empty table becomes an empty dataset. jsoup is designed to create a sensible parse tree even for invalid, tag-soup HTML, but you should still validate that the selected table is the one your contract expects.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsNested content and entities
Element.text() returns visible text from links and lists and decodes HTML entities. If you need URLs, list structure, or a data attribute instead, extract that attribute deliberately rather than mixing presentation text and metadata.
Performance, reliability, and cost decisions
- Parse once: keep the normalized matrix in memory when producing several small outputs.
- Stream large XLSX: switch to
SXSSFWorkbookand clean up temporary files. - Bound network loads: set connection and read timeouts when using
Jsoup.connect; treat timeouts and non-success responses as explicit errors. - Measure your data: no universal accuracy or throughput benchmark applies to every table shape. Test representative pages, span patterns, encodings, and row counts in your environment.
- Make failures observable: record the selector, source URL or file, row count, column count, and output paths.
Troubleshooting
“No table matched”
The selector may target a generated class, an iframe, or a table different from the one you inspected. Print the document’s table count, test a broad table selector, and verify that the HTML you loaded actually contains the rows.
Columns shift after a merged cell
Inspect rowspan and colspan. A converter that ignores spans will shift subsequent values. Expand spans into the rectangular matrix, or document a flattening rule and test it with a fixture.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
JSON keys are duplicated or meaningless
The first row is not a valid header. Use array-of-arrays JSON, or provide an explicit header mapping rather than silently overwriting duplicate keys.
CSV opens as one column or shows garbled characters
Check the delimiter expected by the target program and confirm the file is UTF-8. Ensure fields containing delimiters, quotes, or newlines are quoted and embedded quotes doubled.
Excel changed an ID or removed leading zeroes
Write the value as a text cell, as the example does. Introduce numeric/date types only with explicit coercion rules.
Out-of-memory errors during XLSX creation
Use SXSSFWorkbook, reduce retained rows, avoid creating unnecessary styles, and process one table at a time.
Or skip the browser setup
If your workflow also needs a clean visual capture of the source page, ScreenshotNeo can return a screenshot or PDF through one request. It does not replace jsoup for extracting cell values, but it avoids maintaining browser automation for the visual side of the job. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/table -o shot.webp
See the ScreenshotNeo API documentation for options such as full-page capture, device and viewport settings, custom CSS or JavaScript, waiting for selectors or network idle, request blocking, cookies and headers, PDF page ranges, caching, signed links, asynchronous jobs, and bulk capture. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
FAQ
Frequently Asked Questions
Should I preserve HTML attributes as well as visible text?
Only when your data contract needs them. Keep visible text as the default, then add an explicit attribute-extraction field for links, IDs, or data attributes so presentation and metadata remain distinguishable.
How can I guarantee stable output when a site changes its markup?
Select a stable table identifier, validate expected headers and column count, and fail the job when those checks do not pass instead of exporting a plausible but wrong table.
Can one normalized model support additional formats later?
Yes. Once rows and columns are rectangular and policies are explicit, you can add another writer without changing HTML traversal or span handling.
The Bottom Line
Parse with jsoup, normalize spans and headers once, then reuse that model for Jackson JSON, quoted UTF-8 CSV, and Apache POI XLSX. Explicit policies for ambiguous headers, types, encoding, and large files are what make the exports dependable.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

