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

如何使用Flutter包将JSON数据、表格数据导出至Excel工作表

Dart 基于JSON批量生成对应结构Excel实现

核心实现逻辑

  • 解析JSON结构,提取results字段下的用户数据数组
  • 取单条数据的键集合作为Excel表头,自动生成4个对应列
  • 逐行遍历数据数组,按列匹配键值写入单元格,自动生成所有数据行
  • 保留原有列宽配置、列自适应配置,适配新的列结构

完整实现代码

import 'dart:convert';
import 'package:excel/excel.dart';

Future<void> createExcel(String jsonStr) async {
  // 解析JSON数据
  final Map<String, dynamic> jsonData = jsonDecode(jsonStr);
  final List<dynamic> userList = jsonData['results'] as List;
  if (userList.isEmpty) return; // 空数据兜底,避免运行报错

  final excel = Excel.createExcel();
  final sheet = excel.sheets[excel.getDefaultSheet() as String];

  // 写入表头(第一行,行索引从0开始计数)
  final List<String> columns = userList.first.keys.toList();
  for (var colIndex = 0; colIndex < columns.length; colIndex++) {
    sheet!
        .cell(CellIndex.indexByColumnRow(columnIndex: colIndex, rowIndex: 0))
        .value = columns[colIndex];
    // 默认开启列宽自适应
    sheet.setColAutoFit(colIndex);
  }
  // 保留原有逻辑:给第3列(邮箱列,索引为2)设置固定宽度10
  sheet!.setColWidth(2, 10);

  // 逐行写入业务数据(从第二行开始,行索引从1计数)
  for (var rowIndex = 0; rowIndex < userList.length; rowIndex++) {
    final Map<String, dynamic> rowData = userList[rowIndex];
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      final cellValue = rowData[columns[colIndex]];
      sheet
          .cell(CellIndex.indexByColumnRow(
              columnIndex: colIndex, rowIndex: rowIndex + 1))
          .value = cellValue;
    }
  }

  // 保存生成的Excel文件
  excel.save();
}

适配说明

  • 调用方法时直接传入你的JSON字符串即可自动生成符合要求的4列结构Excel
  • 如果需要自定义列显示顺序、修改表头展示名称,不需要动态取JSON键,可手动定义列映射,示例如下:
    // 自定义列显示名、对应JSON字段顺序示例
    final List<String> columnTitles = ['名', '姓', '邮箱', '手机号'];
    final List<String> jsonKeys = ['first_name', 'last_name', 'email', 'phone'];
    // 写入表头时用columnTitles取值,写入数据时用jsonKeys[colIndex]从JSON对象中取对应值即可
    
  • 如果传入的已经是解析完成的Map结构JSON数据,跳过jsonDecode步骤直接处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 09:12:22