Excel Export in MVC for IE not allowing to open multiple windows
Here is our ExcelExport action that inherits from ActionResult:
public class ExcelResult<Model> : ActionResult
{
string _fileName;
string _viewPath;
Model _model;
ControllerContext _context;
public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model)
{
this._context = context;
this._fileName = fileName;
this._viewPath = viewPath;
this._model = model;
}
protected string RenderViewToString()
{
if (!_viewPath.EndsWith(".aspx"))
{
return _viewPath;
}
using (var writer = new StringWriter())
{
var view = new WebFormView(_context, _viewPath);
var vdd = new ViewDataDictionary<Model>(_model);
var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
void WriteFile(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 = "application/ms-excel";
context.Response.Write(RemoveImages(content));
context.Response.End();
}
public override void ExecuteResult(ControllerContext context)
{
string content = this.RenderViewToString();
this.WriteFile(content);
}
public static string RemoveImages(string html)
{
StringBuilder retval = new StringBuilder();
using (StringReader reader = new StringReader(html))
{
string line = string.Empty;
do
{
开发者_JS百科 line = reader.ReadLine();
if (line != null)
{
if (!line.StartsWith("<img"))
{
retval.Append(line);
}
}
} while (line != null);
}
return retval.ToString();
}
}
The export works fine, but in IE only (works in FF), if you export, and choose to open the file instead of save it, and then click export again right away, it tries to open another file with the same name and therefore Excel won't let you until you close your working document.
In FF however, the name just adds an integer that increments by 1 each time you click export.
What do I have to do to achieve the same functionality in IE?
I faced the same problem and out of the box you cant do anything because that's the way IE and Excel handle this. You are also not able to identify that a file of the same name is already opened. But you can use either JavaScript or the user session to identify that the user has already loaded the export within a timespan and and change the file name on server side for this download. That worked for me after 2 days of searching and mailing.
精彩评论