正在返回字节数组,但未通知最终用户在 Excel 中打开它

本文关键字:Excel 用户 字节数 字节 返回 数组 通知 | 更新日期: 2023-09-27 18:34:02

>我正在尝试从控制器返回一个 csv 文件作为字节数组。 但是,我的IE浏览器没有提示用户在Excel文档中打开此CSV。

这是我的控制器

    private static readonly log4net.ILog log = log4net.LogManager.GetLogger("HomeController.cs");
    public ActionResult GetClientList (int? marketId, int? partnerId, int? statusId, int? officeId)
    {
        List<Engagement> QueryResult = PMService.GetRequestedEngagments(marketId, partnerId, statusId,officeId);
        try
        {
          /* I am sending my query list to a function which
             creates it to a Comma seprated string in order 
             to be become a CSV file.*/
            var writetofile = PMService.BuildCsvString(QueryResult);
            var bytefile = new byte[writetofile.Count()];
            return bytefile;
        }
        catch (Exception ex)
        {
            log.Error(ex);
        }
            return null;
    }

正在返回字节数组,但未通知最终用户在 Excel 中打开它

看起来您的BuildCsvString以字符串形式返回 CSV 文件。因此,您可以将此结果作为用户将下载的 FileResult 返回:

string writetofile = PMService.BuildCsvString(QueryResult);
var bytefile = Encoding.UTF8.GetBytes(writetofile);
return File(bytefile, "text/csv", "test.csv")

您应该使用 FileResult 作为返回类型而不是 ActionResult

例如

public FileResult GetClientList() 
{
   var writetofile = PMService.BuildCsvString(QueryResult);
   var bytefile = Encoding.UTF8.GetBytes(writetofile);
   return File(byteFile, "text/csv","yourFileName.csv");
}