You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Aspose.Cells转换JSON至Excel时遇文件格式不支持异常求助

解决Aspose.Cells加载JSON时“文件格式不支持”的异常

问题根源

直接调用Workbook构造函数加载JSON文件是错误用法——Workbook默认仅识别Excel格式文件(如XLSX、XLS等),JSON不属于它的默认加载范畴,因此会抛出格式不支持异常。另外你代码里用FileWriter(".//Json_files//elastic_search.json", true)的追加模式写入JSON,多次运行后文件会变成非标准JSON结构(多个JSON对象拼接),这也会加剧加载失败的概率。

修复方案

1. 修正JSON文件写入逻辑

去掉追加模式,每次写入时覆盖旧文件,保证JSON结构完整:

// 移除第二个参数true,改为覆盖写入
PrintWriter out1 = new PrintWriter(new FileWriter(".//Json_files//elastic_search.json"), true);
out1.write(resp1.asString());
out1.close();

2. 使用Aspose.Cells的JsonLoadOptions加载JSON

需通过JsonLoadOptions明确指定加载格式为JSON,再传入Workbook构造函数:

// 导入必要类
import com.aspose.cells.JsonLoadOptions;
import com.aspose.cells.LoadFormat;
import com.aspose.cells.Workbook;

// 创建JSON加载选项
JsonLoadOptions loadOptions = new JsonLoadOptions();
loadOptions.setLoadFormat(LoadFormat.JSON);

// 带加载选项初始化Workbook
Workbook workbook = new Workbook(".//Json_files//elastic_search.json", loadOptions);

3. 验证JSON结构合法性

确保API返回的resp1.asString()是标准JSON格式(单个对象或数组),无语法错误。可手动打开生成的JSON文件检查,或用本地工具校验格式。

修正后的核心代码片段

// 写入JSON文件(覆盖模式)
PrintWriter out1 = new PrintWriter(new FileWriter(".//Json_files//elastic_search.json"), true);
out1.write(resp1.asString());
out1.close();

// ... 日期处理、目录创建代码保持不变 ...

// 加载JSON到Workbook
JsonLoadOptions loadOptions = new JsonLoadOptions();
loadOptions.setLoadFormat(LoadFormat.JSON);
Workbook workbook = new Workbook(".//Json_files//elastic_search.json", loadOptions);

// 保存Excel文件
workbook.save(dir + "//ES-" + stockname + "-" + formatedate + ".xlsx");

内容的提问来源于stack exchange,提问作者Ramesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:01:53