0

无论如何要更改从 mvcgrid 下载的 csv 文件扩展名?它以 .csv 格式下载,我希望 .txt 阻止我的用户在 excel 中打开内容?

我可以看到有一个自定义渲染引擎,但它似乎提供文件内容格式而不是扩展名。

谢谢

4

1 回答 1

0

通过定制引擎对其进行管理

using MVCGrid.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MVCGrid.Web.Models
{
    public class TextExportEngine : IMVCGridRenderingEngine
    {
        public bool AllowsPaging
        {
            get { return false; }
        }

        public void PrepareResponse(HttpResponse httpResponse)
        {
            httpResponse.Clear();
            httpResponse.ContentType = "text/comma-separated-values";
            httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".txt\"");
            httpResponse.BufferOutput = false;
        }

        public void Render(MVCGrid.Models.RenderingModel model, MVCGrid.Models.GridContext gridContext, System.IO.TextWriter outputStream)
        {
            var sw = outputStream;

            StringBuilder sbHeaderRow = new StringBuilder();
            foreach (var col in model.Columns)
            {
                if (sbHeaderRow.Length != 0)
                {
                    sbHeaderRow.Append(",");
                }
                sbHeaderRow.Append(Encode(col.Name));
            }
            sbHeaderRow.AppendLine();
            sw.Write(sbHeaderRow.ToString());

            foreach (var item in model.Rows)
            {
                StringBuilder sbRow = new StringBuilder();
                foreach (var col in model.Columns)
                {
                    var cell = item.Cells[col.Name];

                    if (sbRow.Length != 0)
                    {
                        sbRow.Append(",");
                    }

                    string val = cell.PlainText;

                    sbRow.Append(Encode(val));
                }
                sbRow.AppendLine();
                sw.Write(sbRow.ToString());
            }
        }

        private string Encode(string s)
        {
            if (String.IsNullOrWhiteSpace(s))
            {
                return "";
            }

           
            return s;
        }

        public void RenderContainer(MVCGrid.Models.ContainerRenderingModel model, System.IO.TextWriter outputStream)
        {
        }
    }
}

然后将以下内容添加到我的网格定义中

                .AddRenderingEngine("tabs", typeof(TextExportEngine)
于 2020-07-10T06:03:45.477 回答