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

XLWorkbook生成Excel不存本地发邮件后无法打开问题求助

问题解决:XLWorkbook生成的Excel作为邮件附件异常

核心问题

你的代码存在两个关键错误,导致附件为空且无法正常打开:

  1. MemoryStream位置未重置:调用workbook.SaveAs(ms)后,流的读写指针停在流的末尾,后续Attachment读取时从该位置开始,自然读不到任何内容。
  2. Content-Type类型错误:application/excel是旧版MIME类型,针对xlsx格式,需使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet才准确。

修正后的代码

try
{
    MemoryStream ms = new MemoryStream();
    workbook.SaveAs(ms);
    // 重置流的读写位置到起始点,确保附件能读取完整内容
    ms.Position = 0;

    MailAddress from = new MailAddress(emailfFrom, "Me");
    MailAddress to = new MailAddress(emailTo);

    MailMessage m = new MailMessage(from, to);
    m.Subject = "Test";
    m.Body = "<h2>Some text here</h2>";
    m.IsBodyHtml = true;

    // 使用xlsx格式对应的标准MIME类型
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, "file.xlsx", contentType);
    
    // 显式设置附件文件名,避免邮件客户端丢失扩展名
    attach.ContentDisposition.FileName = "file.xlsx";
    m.Attachments.Add(attach);
             
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.Credentials = new NetworkCredential(emailfFrom, password);
    smtp.EnableSsl = true;
    smtp.Send(m);
    
    // 释放流资源
    ms.Dispose();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

额外补充

  • 关于.xls格式:XLWorkbook(基于EPPlus库)仅支持OpenXML格式(xlsx),若需生成.xls格式,需切换到支持BIFF格式的库,比如NPOI或Microsoft.Office.Interop.Excel。
  • 资源优化:推荐用using语句包裹MemoryStream,自动释放资源:
using (MemoryStream ms = new MemoryStream())
{
    workbook.SaveAs(ms);
    ms.Position = 0;
    // 后续邮件发送逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:10:35