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

Flutter使用excel库设置Excel单元格货币格式时文件损坏求助

Flutter excel库自定义货币格式(卢布/美元)解决方案

问题说明

用Flutter的excel库做表格时,发现自带的NumFormat类没提供卢布、美元这类货币的格式化选项。自己试了两种自定义格式的写法,结果整个Excel文件和样式都损坏了,代码如下:
第一种写法:

sheet.cell(CellIndex.indexByString('E$rowIndex')).cellStyle = CellStyle(
  numberFormat: NumFormat.custom(formatCode: '#,##0 ₽'),
);

第二种写法:

sheet.cell(CellIndex.indexByString('E$rowIndex')).cellStyle = CellStyle(
  numberFormat: CustomNumericNumFormat(formatCode: '# ##0,00 ₽'),
);

解决办法

  1. 按Excel原生规范写格式代码
    Excel的自定义货币格式有固定语法,还要注意符号的编码问题,推荐两种写法:
  • 卢布:用#,##0.00 \₽ 或者Unicode编码#,##0.00 \u20BD
  • 美元:直接用#,##0.00 $
  1. 认准NumFormat.custom,别用CustomNumericNumFormat
    部分版本的库对CustomNumericNumFormat支持有兼容性问题,用NumFormat.custom更稳妥,正确代码示例:
// 设置卢布格式
sheet.cell(CellIndex.indexByString('E$rowIndex')).cellStyle = CellStyle(
  numberFormat: NumFormat.custom(formatCode: '#,##0.00 \\₽'),
);

// 设置美元格式
sheet.cell(CellIndex.indexByString('F$rowIndex')).cellStyle = CellStyle(
  numberFormat: NumFormat.custom(formatCode: '#,##0.00 $'),
);
  1. 别乱加格式代码里的空格
    之前代码里的# ##0,00 ₽这种空格会导致解析错误,用标准的千分位分隔符,、小数点.,如果要适配区域格式再调整。

  2. 保存文件步骤别出错
    设置完样式后,按正确方式保存Excel文件:

final file = File('output.xlsx');
await file.writeAsBytes(excel.encode()!);

额外提醒

  • 要是直接写卢布符号₽不行,就换成Unicode转义符\u20BD,避免编码乱码
  • 别反复给同一个单元格设置样式,容易引发样式冲突
  • 测试时先做个只有几行的简单表格,排查是不是样式叠加导致文件损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:31:12