将列表导出到Excel和OpenOffice

时间:2015-11-02 14:28:06

标签: asp.net-mvc excel

我有一个列表,我需要在excel中导出数据。视图中的代码:

 $("#btnExport").click(function () {
        //Used for Export to excel
         window.open('@Url.Action("ExportHotelUtilizationListToExcel","DutyTravel")');

    });

<input type="button" value="Export to Excel" name="submitButton" id="btnExport" class="k-button" />

以下是我的控制器方法

 public FileResult ExportHotelUtilizationListToExcel()
        {
            var grid = new System.Web.UI.WebControls.GridView();
            
            List<DutyTravelHotelUtilization> lstSeparation = null;
            if (Session["HotelUtilizationDetails"] != null)
            {
                lstSeparation = (List<DutyTravelHotelUtilization>)HttpContext.Session["HotelUtilizationDetails"];
                grid.DataSource = from d in lstSeparation
                                    select new
                                    {
                                        RequestCode = d.DutyTravelReqId,
                                        StffNumber = d.StaffNumber,
                                        StaffName = d.StaffName,
                                        CityCode = d.CityCode,
                                        CityName = d.CityName,
                                        HotelCategory = d.HotelCategory,
                                        HotelName = d.HotelName,
                                        CurrencyInQAR = d.QurrencyQAR,
                                        CheckInDate = Convert.ToDateTime(d.CheckInDate).ToString("dd-MMM-yyyy"),
                                        CheckOutDate = Convert.ToDateTime(d.CheckOutDate).ToString("dd-MMM-yyyy"),
                                        Duration = d.Duration
                                    };
            }
            grid.DataBind();
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grid.RenderControl(htw);
            return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Contacts.xlsx");
        }

它显示下载选项,能够在OpenOffice中打开,但在MS Office 2010中显示有关某些格式问题的错误消息。

0 个答案:

没有答案