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

Java中将含\n\t的JSON响应存入二维数组并用POI写入Excel

从JSON字符串响应提取表格数据并写入Excel实现方案

需求规则

拿到单字符串格式的JSON响应后,需先将其中的表格内容提取为二维数组,再写入Excel,具体规则如下:

  • 响应内的\t为单元格分隔符,遇到时在当前行新增单元格写入内容
  • 响应内的\n为行分隔符,遇到时新增一行写入内容
  • 最终使用Apache POI完成二维数组到Excel文件的写入

响应示例

入参JSON结构参考:

"type": "TABLE",
"data": "Col_1\tCol_2\tCol_3\nName_1\tPlace_1\tAnimal_1\nName_2\tPlace_2\tAnimal_2\nName_3\tPlace_3\tAnimal_3\n"

完整实现步骤

步骤1:解析JSON提取原始数据

先解析JSON响应,取出data字段对应的原始字符串。

步骤2:原始字符串转二维数组

按分隔符拆分字符串生成二维数组,注意过滤末尾多余换行产生的空行:

// dataStr为解析后得到的data字段字符串值
List<List<String>> tableData = new ArrayList<>();
// 按换行符拆分所有行
String[] rows = dataStr.split("\n");
for (String row : rows) {
    // 跳过空行
    if (row.trim().isEmpty()) {
        continue;
    }
    // 按制表符拆分当前行的所有单元格
    String[] cells = row.split("\t");
    tableData.add(Arrays.asList(cells));
}

步骤3:引入Apache POI依赖

Maven项目在pom.xml中添加如下依赖,版本可根据项目需要调整:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

步骤4:二维数组写入Excel

遍历二维数组内容写入Excel工作表:

// 创建xlsx格式工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("表格数据");
// 逐行写入内容
for (int rowIndex = 0; rowIndex < tableData.size(); rowIndex++) {
    Row currentRow = sheet.createRow(rowIndex);
    List<String> cellValues = tableData.get(rowIndex);
    // 逐单元格写入内容
    for (int cellIndex = 0; cellIndex < cellValues.size(); cellIndex++) {
        Cell currentCell = currentRow.createCell(cellIndex);
        currentCell.setCellValue(cellValues.get(cellIndex));
    }
}
// 可选:自动适配列宽
for (int cellIndex = 0; cellIndex < tableData.get(0).size(); cellIndex++) {
    sheet.autoSizeColumn(cellIndex);
}
// 输出到本地文件
try (FileOutputStream outputStream = new FileOutputStream("导出结果.xlsx")) {
    workbook.write(outputStream);
} finally {
    workbook.close();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:15:00