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

.NET 8 AWS Lambda生成Excel时缺失字体问题求助

AWS Lambda .NET8 + NPOI 字体缺失问题解决(AutoSizeRow报错)

问题重现

运行在AWS Lambda上的.NET8 C#应用,使用NPOI 2.7.0生成Excel文件,调用worksheet.AutoSizeRow(rowIndex)时抛出错误:

SixLabors.Fonts.FontException: No fonts found installed on the machine.

此前.NET6版本功能正常,已尝试添加SixLabors.Fonts 2.0.3无效,不希望使用Docker镜像。

解决方案

方法1:嵌入字体文件并手动注册(推荐)

无需修改Lambda环境,直接将字体打包到代码中:

  • 准备TrueType字体文件(如arial.ttf、Noto Sans等开源字体)
  • 将字体文件添加到项目,设置复制到输出目录为「始终复制」
  • 在调用AutoSizeRow前注册字体:
// 注册嵌入的字体
var fontPath = Path.Combine(Environment.CurrentDirectory, "arial.ttf");
if (File.Exists(fontPath))
{
    var fontCollection = new FontCollection();
    fontCollection.Add(fontPath);
    Fonts.Configure(options => options.SetFontCollection(fontCollection));
}

注意:Lambda工作目录为代码包根目录,确保路径正确;多字体可重复添加到集合。

方法2:修改NPOI配置跳过字体检测(适合非精确行高场景)

若不需要精确自动行高,可直接禁用字体依赖:

// 创建workbook前设置默认字体名
NPOI.SS.UserModel.FontManager.DefaultFontName = "Arial";

// 或调用AutoSizeRow时跳过字体高度检查(需NPOI支持该参数)
worksheet.AutoSizeRow(rowIndex, skipFontHeightCheck: true);

注意:skipFontHeightCheck为NPOI新版本特性,若2.7.0不支持,可升级NPOI至兼容.NET8的稳定版。

方法3:通过Lambda层添加字体

无需修改代码,将字体打包为Lambda层挂载到函数:

  1. 创建fonts/目录,放入所需字体文件
  2. 将目录打包为zip,上传为AWS Lambda层
  3. 为Lambda函数添加该层,字体将挂载到/opt/fonts/路径
  4. 在代码中注册路径下的字体:
var fontDir = "/opt/fonts/";
if (Directory.Exists(fontDir))
{
    var fontCollection = new FontCollection();
    foreach (var fontFile in Directory.GetFiles(fontDir, "*.ttf"))
    {
        fontCollection.Add(fontFile);
    }
    Fonts.Configure(options => options.SetFontCollection(fontCollection));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:02:12