MVC3导出到excel - lambda表达式改变编码

时间:2013-11-04 08:28:21

标签: asp.net-mvc-3 export-to-excel

我正在使用实体框架。 我以这种方式将表导出为ex​​cel:

DetailsSet TheDetails = db.DetailsSet.SingleOrDefault(x => x.Id == id);
            string filename = Guid.NewGuid() + ".xls";
            StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            // var List = db.GetRegList(TheDetails.CorrectAnswer);
            List<RegistrationSet> RegList = TheDetails.RegistrationSet.Where(x => x.Answer == TheDetails.CorrectAnswer).ToList();
            dgGrid.DataSource = RegList;
            dgGrid.DataBind();
            dgGrid.RenderControl(hw);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

            Response.Write(tw.ToString());
            Response.End();

问题在于,在excel中,来自db的希伯来语中的所有文本都显示为gibresh。  当我从网格中删除.Where(x => x.Answer == TheDetails.CorrectAnswer)时,excel就可以了 - 意味着希伯来语中的所有文本都可以。

喜欢这样就可以了:

List<RegistrationSet> RegList = TheDetails.RegistrationSet.ToList();

但是像这样,不行:

List<RegistrationSet> RegList = TheDetails.RegistrationSet.Where(x => x.Answer == TheDetails.CorrectAnswer).ToList();

OK功能的完整示例:

DetailsSet TheDetails = db.DetailsSet.SingleOrDefault(x => x.Id == id);
            string filename = Guid.NewGuid() + ".xls";
            StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            // var List = db.GetRegList(TheDetails.CorrectAnswer);
            List<RegistrationSet> RegList = TheDetails.RegistrationSet.ToList();
            dgGrid.DataSource = RegList;
            dgGrid.DataBind();
            dgGrid.RenderControl(hw);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

            Response.Write(tw.ToString());
            Response.End();

1 个答案:

答案 0 :(得分:0)

Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble()); 

解决了问题