.net core api 生成csv文件并文件流输出

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.GetEncoding("GB2312"));
var merchantName = db_list[0].MerchantName;
//生成标题
writer.Write("行程单号,日期,司机,支付方式,费用");
writer.WriteLine();
//循环生成主体详情
foreach (var item in db_list)
{
    //加"\t":在csv文件中加上\t标识禁止转义,如不加,数字会被转掉
    writer.Write("\t" + item.OrderNumber + "," + "\t" + item.CreateDt + "," + "\t" + item.DriverName + "," + "\t" + item.PayMethod + "," + "\t" + item.PayAmount);
    writer.WriteLine();
}
writer.Flush();
stream.Position = 0;

var actionresult = new FileStreamResult(stream, new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("text/csv"));
actionresult.FileDownloadName = "【" + merchantName + "】订单详情" + System.DateTime.Now.ToString("yyMMddHHmm") + ".csv";
return actionresult;

你可能感兴趣的:(.netcore)