将 Excel 电子表格转换为 JSON 是在构建数据交换管道或为 API 提供数据时的常见需求。 Conholdate.Total for Java 是一个强大的 SDK,简化了 Java 开发者的此类任务。在本指南中,您将学习如何设置库,完整实现整个过程,并微调转换选项以匹配项目需求。

Conholdate.Total for Java 的先决条件和设置

在开始之前,请确保您拥有:

  • 已安装 Java 17 或更高版本。
  • 用于依赖管理的 Maven 3.6+。
  • 您想要转换的 Excel 文件(.xlsx)。

将 Conholdate.Total Maven 仓库和依赖添加到您的 pom.xml

<repositories>
    <repository>
        <id>conholdate-repo</id>
        <name>Conholdate Maven Repository</name>
        <url>https://repository.conholdate.com/repo/</url>
    </repository>
</repositories>

<dependency>
    <groupId>com.conholdate</groupId>
    <artifactId>conholdate-total</artifactId>
    <version>24.9</version>
    <type>pom</type>
</dependency>

您也可以直接从下载页面下载最新的 JAR 包。准备好 SDK 后,您即可在 Java 中开始 Excel 转 JSON 的转换。

Excel 转 JSON 转换(Java):逐步演练

步骤 1:加载源 Excel 文档

首先,指定源 XLSX 文件的路径并创建一个 Conversion 实例。try‑with‑resources 块确保正确释放转换对象。

String inputFile = "sample.xlsx";
try (Conversion conversion = new Conversion(inputFile)) {
    // conversion object ready
}

步骤 2:配置 JSON 转换选项

创建一个 JsonConvertOptions 对象并调整设置,例如漂亮打印、包含标题、自定义日期和数字格式以及批处理大小。这些选项控制 Java 中将 Excel 转换为 JSON 的方式,从而决定最终输出。

JsonConvertOptions jsonOptions = new JsonConvertOptions();
jsonOptions.setPrettyPrint(true);
jsonOptions.setIncludeHeaders(true);
jsonOptions.setDateFormat(JsonConvertOptions.DateFormat.CUSTOM);
jsonOptions.setCustomDateFormat("yyyy-MM-dd");
jsonOptions.setNumberFormat(JsonConvertOptions.NumberFormat.CUSTOM);
jsonOptions.setCustomNumberFormat("#.##");
jsonOptions.setRowsPerBatch(5000);

第3步:执行转换

提供目标 JSON 文件名并调用 convert 方法。SDK 在内部处理转换。

String outputFile = "sample.json";
conversion.convert(outputFile, jsonOptions);

第4步:处理结果并清理

转换后,输出确认消息。任何异常都会被捕获并打印到控制台。

System.out.println("Conversion completed successfully. JSON saved to: " + outputFile);
} catch (Exception e) {
    System.err.println("Error during Excel to JSON conversion:");
    e.printStackTrace();
}

通过这些步骤,Java 中的 Excel 转 JSON 转换已完成,您可以将生成的 JSON 集成到您的 API 或数据处理工作流中。

完整实现:Java Excel 转 JSON 转换

以下示例演示如何在 Java 中使用 Conholdate.Total for Java 执行 excel 到 JSON 的转换。

import com.groupdocs.conversion.Conversion;
import com.groupdocs.conversion.options.convert.JsonConvertOptions;
import com.groupdocs.conversion.options.convert.JsonConvertOptions.DateFormat;
import com.groupdocs.conversion.options.convert.JsonConvertOptions.NumberFormat;

public class ExcelToJsonDemo {
    public static void main(String[] args) {
        // Input Excel file (generic path)
        String inputFile = "sample.xlsx";
        // Desired JSON output file
        String outputFile = "sample.json";

// Perform conversion inside try‑with‑resources to ensure proper cleanup
        try (Conversion conversion = new Conversion(inputFile)) {

// Configure JSON conversion options
            JsonConvertOptions jsonOptions = new JsonConvertOptions();

// Pretty‑print the JSON for readability
            jsonOptions.setPrettyPrint(true);

// Include column headers as JSON property names
            jsonOptions.setIncludeHeaders(true);

// Define how dates and numbers should be formatted in the JSON output
            jsonOptions.setDateFormat(DateFormat.CUSTOM);
            jsonOptions.setCustomDateFormat("yyyy-MM-dd");
            jsonOptions.setNumberFormat(NumberFormat.CUSTOM);
            jsonOptions.setCustomNumberFormat("#.##");

// Optional performance tweak: limit rows processed per batch (useful for very large sheets)
            jsonOptions.setRowsPerBatch(5000);

// Execute the conversion
            conversion.convert(outputFile, jsonOptions);

System.out.println("Conversion completed successfully. JSON saved to: " + outputFile);
        } catch (Exception e) {
            // Basic error handling – in production code you might want more sophisticated logging
            System.err.println("Error during Excel to JSON conversion:");
            e.printStackTrace();
        }
    }
}

注意: 此代码示例演示了核心功能。在将其用于项目之前,请确保更新所有文件路径和配置值以匹配实际环境,验证已正确安装所有必需的依赖项,并在开发环境中彻底测试。如果遇到任何问题,请参阅官方文档或联系支持团队获取帮助。

转换选项和设置

SDK 提供了多个选项来定制 JSON 输出:

  • Pretty Print - 通过添加缩进来提高可读性。

    jsonOptions.setPrettyPrint(true);
    
  • Include Headers - 使用工作表的第一行作为属性名称。
    setIncludeHeaders(true)(参见API 参考)。

  • Custom Date Format - 定义日期模式,例如 "yyyy-MM-dd"
    setCustomDateFormat("yyyy-MM-dd")

  • Custom Number Format - 控制数字精度,例如 "#.##"
    setCustomNumberFormat("#.##")

调整这些设置可让您将生成的 JSON 与下游服务或数据库的期望保持一致。

结论

您现在拥有一个由 Conholdate.Total for Java 提供支持的 Java 实现的 Excel 转 JSON 转换功能。SDK 负责繁重的工作,而可配置选项让您能够控制格式和性能。请记得为生产环境获取合适的许可证;您可以请求 临时许可证页面 来评估该库,或查看完整的 定价页面 了解商业条款。祝编码愉快!

FAQs

  • 如何在 Java 中使用 Conholdate.Total 执行 Excel 到 JSON 的转换?
    使用 Conversion 类和 JsonConvertOptions,如代码示例所示。SDK 抽象了文件处理,并提供了一个单一的 convert 调用。

  • 在 Java 中将 Excel 转换为 JSON 时,我可以自定义日期和数字格式吗?
    可以。setCustomDateFormatsetCustomNumberFormat 方法允许您定义符合目标系统期望的模式。

  • Conholdate.Total for Java 有哪些许可选项?
    您可以从临时许可页面获取临时评估许可证,或通过定价页面购买完整许可证。

  • 是否支持对大型 Excel 文件进行批处理?
    setRowsPerBatch 选项允许您将工作表分块处理,这对于批量转换场景非常理想。

阅读更多