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

如何在Flutter中生成并保存docx文件?求docx_template可用示例

解决docx_template报错+完整使用示例

先处理你遇到的FormatException: Could not find End of Central Directory Record错误

这个错误基本是模板文件或读取逻辑的问题:

  • 别用WPS生成的docx当模板,兼容性差,直接用微软Word新建空白文档,保存为标准.docx格式
  • 检查pubspec.yaml的asset配置,模板文件路径要完全匹配,比如模板放assets/template.docx,配置需写:
    assets:
      - assets/template.docx
    
  • 读取asset时用rootBundle.load()完整获取字节流,避免手动截取导致文件损坏

docx_template完整使用示例

1. 依赖配置

在pubspec.yaml中添加:

dependencies:
  flutter:
    sdk: flutter
  docx_template: ^1.0.0 # 使用最新稳定版本
  permission_handler: ^10.2.0 # 用于申请存储权限
  path_provider: ^2.0.11 # 获取设备存储路径

2. 模板准备

用Word新建空白文档,插入占位符示例:

姓名:{{name}}
年龄:{{age}}
职位:{{job}}
保存为assets/template.docx并放入对应目录

3. 核心代码

import 'dart:io';
import 'package:flutter/services.dart';
import 'package:docx_template/docx_template.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';

Future<void> generateAndSaveDocx() async {
  // 申请存储权限
  final status = await Permission.storage.request();
  if (!status.isGranted) return;

  // 读取模板字节流
  final assetBytes = await rootBundle.load('assets/template.docx');
  final templateBytes = assetBytes.buffer.asUint8List(
    assetBytes.offsetInBytes,
    assetBytes.lengthInBytes
  );

  // 准备填充数据
  final fillData = {
    'name': '张三',
    'age': '28',
    'job': 'Flutter开发工程师'
  };

  // 渲染并生成docx
  final docx = DocxTemplate(templateBytes);
  await docx.render(fillData);
  final resultBytes = docx.save();

  // 保存到设备外部存储
  final storageDir = await getExternalStorageDirectory();
  final targetFile = File('${storageDir?.path}/generated_profile.docx');
  await targetFile.writeAsBytes(resultBytes);
}

额外注意点

  • Android 13+需适配READ_MEDIA_IMAGES等新权限,具体参考permission_handler官方说明
  • 如果仍报错,重新另存模板文件,清除隐藏格式错误
  • 禁止将.doc文件改后缀为.docx当模板,必须是标准docx格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:05:34