通过显示“另存为”对话框保存HTML报告

时间:2012-08-17 04:22:46

标签: asp.net-mvc save

我想在我的MVC应用程序中向用户显示“另存为”对话框,并允许他以pdf或word格式保存一些HTML报告。为此,我是否需要在服务器端使用文件流和IO功能?或者它可能在JQuery级别本身?

我在网上找到了一些引用,比如添加响应标头Content-Disposition,但没有得到如何应用它。你能建议一些选择吗?

1 个答案:

答案 0 :(得分:0)

您必须从ActionResult创建一个以所需方式播放输出的后代。

这是我为实现“另存为Excel”功能而创建的一类:

            public class ExcelResult : ActionResult
            {
                private string _fileName;
                private IQueryable _rows;
                private string[] _headers = null;
                private string _data;

                private TableStyle _tableStyle;
                private TableItemStyle _headerStyle;
                private TableItemStyle _itemStyle;

                public string FileName
                {
                    get { return _fileName; }
                }

                public IQueryable Rows
                {
                    get { return _rows; }
                }



                public ExcelResult(string data, string fileName)
                {
                    _fileName = fileName;
                    _data = data;
                }

                public override void ExecuteResult(ControllerContext context)
                {
                    WriteFile(_fileName, "application/ms-excel", _data);            
                }


                private string ReplaceSpecialCharacters(string value)
                {
                    value = value.Replace("’", "'");
                    value = value.Replace("“", "\"");
                    value = value.Replace("”", "\"");
                    value = value.Replace("–", "-");
                    value = value.Replace("…", "...");
                    return value;
                }

                private void WriteFile(string fileName, string contentType, string content)
                {
                    HttpContext context = HttpContext.Current;
                    context.Response.Clear();
                    context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    context.Response.Charset = "";
                    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    context.Response.ContentType = contentType;
                    context.Response.Write(content);
                    context.Response.End();
                }
            }

您可以使用此示例为单词生成HTML。 PDF是另一回事,'。