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

ASP.NET C#中为ReportViewer生成的PDF/Excel设置固定文件名

如何设置导出文件的固定名称?

你只需要调整代码里返回File的那一行,使用File方法的重载版本,指定第三个参数作为固定文件名即可。具体操作如下:

  1. 根据当前的导出格式(Format变量的值)生成对应的固定文件名
  2. 在return File时传入这个文件名参数

修改后的完整代码如下:

public ActionResult print(ParametrosGeneral param, string id, FormCollection TipoReporte) { 
    string Format = "pdf"; // string Format = "excel"; 
    LocalReport lr = new LocalReport(); 
    string path = System.IO.Path.Combine(Server.MapPath("~/Reportes"), "Libro.rdlc"); 
    if (System.IO.File.Exists(path)) { 
        lr.ReportPath = path; 
    } else { 
        return View("Index"); 
    } 
    ReportDataSource rd = new ReportDataSource("DSLibro", LibroVenta(4, 2018).Tables[0]); 
    lr.DataSources.Add(rd); 
    string reportType = Format; 
    string mineType; 
    string encoding; 
    string fileNameExtension; 
    string deviceInfo = "<DeviceInfo>" + 
                        "<OutputFormat>" + Format + "</OutputFormat>" + 
                        "<PageWidth>11in</PageWidth>" + 
                        "<PageHeight>8.5in</PageHeight>" + 
                        "<MarginTop>0,787402in</MarginTop>" + 
                        "<MarginLeft>0,787402in</MarginLeft>" + 
                        "<MarginRight>0,787402in</MarginRight>" + 
                        "<MarginBottom>0,787402in</MarginBottom>" + 
                        "</DeviceInfo>"; 
    Warning[] warnings; 
    string[] streams; 
    byte[] renderedBytes; 
    renderedBytes = lr.Render( 
        reportType, 
        deviceInfo, 
        out mineType, 
        out encoding, 
        out fileNameExtension, 
        out streams, 
        out warnings); 
    
    // 新增:根据格式设置固定文件名
    string fileName = Format.Equals("pdf", StringComparison.OrdinalIgnoreCase) ? "rodo.pdf" : "rodo.excel";
    // 修改:传入文件名参数
    return File(renderedBytes, mineType, fileName); 
}

关键修改说明:

  • 新增了fileName变量,根据Format的值判断导出类型,分别设置为rodo.pdf或rodo.excel(使用StringComparison.OrdinalIgnoreCase是为了兼容格式字符串大小写不一致的情况)
  • 将原来的return File(renderedBytes, mineType);改成return File(renderedBytes, mineType, fileName);,第三个参数就是浏览器预览/下载时会使用的默认文件名

这样用户操作文件时,默认名称就会是你想要的固定名称了。

内容的提问来源于stack exchange,提问作者rodrigo.rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:32:05