예제 #1
0
        public void ExportBookersToExcel()
        {
            var bookers = new System.Data.DataTable("bookers");

            bookers.Columns.Add("Фамилия", typeof(string));
            bookers.Columns.Add("Имя", typeof(string));
            bookers.Columns.Add("Email", typeof(string));
            bookers.Columns.Add("Телефон", typeof(string));
            bookers.Columns.Add("Забронированные места", typeof(string));
            bookers.Columns.Add("Приглашающее лицо", typeof(string));
            bookers.Columns.Add("Фуршет", typeof(string));

            var bookerList = GetBookersAndSeats();

            bookerList.ForEach(b =>
            {
                bookers.Rows.Add(b.LastName, b.FirstName, b.Email, b.PhoneNumber, String.Join(" ", b.Seats), b.Face, (b.Party ?? false) ? "Фуршет" : "");
            });

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = bookers;
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Bookers.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #2
0
 public void Export()
 {
     try
     {
         var grid    = new System.Web.UI.WebControls.GridView();
         var product = db.Product.Include(p => p.Category).ToList();
         grid.DataSource = from d in product
                           select new
         {
             id          = d.id,
             name        = d.Name,
             category    = d.Category.Name,
             price       = d.Price,
             count       = d.Count,
             description = d.Description
         };
         grid.DataBind();
         Response.ClearContent();
         Response.AddHeader("Content-Disposition", "filename=Export.xls");
         Response.ContentType = "application/vnd.ms-excel";
         StringWriter   sw  = new StringWriter();
         HtmlTextWriter htw = new HtmlTextWriter(sw);
         grid.RenderControl(htw);
         Response.Write(sw.ToString());
         Response.End();
     }
     catch (Exception ex)
     {
         ViewBag.Error = ex.ToString();
     }
 }
예제 #3
0
        public static void ExportExcelFile(string fileName, DataTable dataSource)
        {
            System.Web.UI.WebControls.GridView dgExport   = null;
            System.Web.HttpContext             curContext = System.Web.HttpContext.Current;
            //IO is used to export and return Excel
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dataSource != null)
            {
                //Set encoding and attachment format
                curContext.Response.Clear();
                curContext.Response.Buffer = true;
                //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)

                //Note: The above code line is used to avoid unreadable code to appearing in file.

                curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
                curContext.Response.ContentType = "application/vnd.ms-excel";
                //Avoid unreadable code to appearing in contents exported.
                curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
                //Export to Excel
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                //Redefine one GridView without paging to solve the problem that there is paging in daData.
                dgExport             = new System.Web.UI.WebControls.GridView();
                dgExport.DataSource  = dataSource;
                dgExport.AllowPaging = false;
                dgExport.DataBind();
                //Download to server.
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
        public void ExportXls(String strPesquisa)
        {
            if (String.IsNullOrEmpty(strPesquisa))
            {
                strPesquisa = String.Empty;
            }

            ViewData["termo"] = strPesquisa;

            var usuarioregional = db.UsuarioRegional.ToList();
            //Codigo Gerou na Index desta Controller (Final da Página)

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = from _data in usuarioregional select _data;
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=usuarioregional.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        /// <summary>
        /// Autor: jlucero
        /// Fecha: 2015-06-16
        /// </summary>
        /// <param name="__a"></param>
        /// <returns></returns>
        ///

        public ActionResult Descarga()
        {
            var grid       = new System.Web.UI.WebControls.GridView();
            var collection = new NOperario().NLista();

            grid.DataSource = from d in collection
                              select new
            {
                ID                  = d.ope_id,
                DOCUMENTO           = d.ope_documento,
                APELLIDOS_Y_NOMBRES = d.ope_nombre,
                TIPO_USUARIO        = d.ope_tipo_usuario,
                CELULAR             = d.ope_celular,
                ESTADO              = (d.ope_estado == 2 ? "Inactivo" : "Activo")
            };
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Operario_Listado.xls");
            Response.ContentType = "application/x-ms-excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return(null);
        }
예제 #6
0
        public ActionResult DescargarGastosMensuales(DateTime mesano)
        {
            if (!((SUM.Models.Usuario)Session["Usuario"]).fl_administrador)
            {
                return(RedirectToAction("Index", "Home"));
            }
            var gv = new System.Web.UI.WebControls.GridView();
            var gastosMensuales = db.sp_GastosMensuales(mesano, GetUsuario().cd_consorcio).OrderBy(x => x.cd_usuario).ToList();

            gv.DataSource = gastosMensuales;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=GastosMensuales" + mesano.ToString("MM-yyyy") + ".xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset     = "";
            System.IO.StringWriter       objStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter objHtmlTextWriter = new System.Web.UI.HtmlTextWriter(objStringWriter);
            Response.Output.WriteLine("<b>Gastos Mensuales del consorcio " + GetUsuario().Consorcio.tx_descripcion + "</b>");
            Response.Output.WriteLine("<br>");
            Response.Output.WriteLine("<u>Periodo " + mesano.ToString("MM-yyyy") + "</u>");
            Response.Output.WriteLine("<br>");
            gv.RenderControl(objHtmlTextWriter);
            Response.Output.WriteLine(objStringWriter.ToString());
            Response.Output.WriteLine("<br>");
            Response.Flush();
            Response.End();
            return(Redirect("GastosMensuales"));
        }
예제 #7
0
        public void CreateExcel(DataTable ds, string FileName)
        {
            System.Web.UI.WebControls.GridView dgExport = null;
            //当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            //IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (ds != null)
            {
                //设置编码和附件格式
                //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
                curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                curContext.Response.ContentType     = "application nd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                curContext.Response.Charset         = "GB2312";

                //导出Excel文件
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
                dgExport             = new System.Web.UI.WebControls.GridView();
                dgExport.DataSource  = ds.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                //下载到客户端
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
예제 #8
0
        /// <summary>
        /// Autor: jlucero
        /// Fecha: 2015-06-16
        /// </summary>
        /// <param name="__a"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult Descarga(string __a)
        //{
        //    Int32 _fila = 2;
        //    String _servidor;
        //    String _ruta;

        //    //if (__a.Length == 0)
        //    //{
        //    //    return View();
        //    //}



        //    List<Observacion> _lista = MvcApplication._Deserialize<List<Observacion>>(__a);

        //    _servidor = String.Format("{0:ddMMyyyy_hhmmss}.xlsx", DateTime.Now);
        //    _ruta = Path.Combine(Server.MapPath("/Temp"), _servidor);

        //    FileInfo _file = new FileInfo(_ruta);
        //    if (_file.Exists)
        //    {
        //        _file.Delete();
        //        _file = new FileInfo(_ruta);
        //    }

        //    using (Excel.ExcelPackage oEx = new Excel.ExcelPackage(_file))
        //    {
        //        Excel.ExcelWorksheet oWs = oEx.Workbook.Worksheets.Add("Observacion");

        //        oWs.Cells[1, 1].Value = "ID";
        //        oWs.Cells[1, 2].Value = "ABREVIATURA";
        //        oWs.Cells[1, 3].Value = "DESCRIPCION";
        //        oWs.Cells[1, 4].Value = "GRUPO";
        //        oWs.Cells[1, 5].Value = "";

        //        foreach (Observacion oBj in _lista)
        //        {
        //            oWs.Cells[_fila, 1].Value = oBj.obs_id;
        //            oWs.Cells[_fila, 2].Value = oBj.obs_abreviatura;
        //            oWs.Cells[_fila, 3].Value = oBj.obs_descripcion;
        //            oWs.Cells[_fila, 4].Value = oBj.gde_descripcion;
        //            oWs.Cells[_fila, 5].Value = (oBj.obs_estado == 2 ? "Inactivo" : "Activo");

        //            _fila++;
        //        }

        //        oWs.Row(1).Style.WrapText = true;
        //        oWs.Row(1).Style.Font.Bold = true;
        //        oWs.Row(1).Style.HorizontalAlignment = Style.ExcelHorizontalAlignment.Center;
        //        oWs.Row(1).Style.VerticalAlignment = Style.ExcelVerticalAlignment.Center;

        //        oWs.Column(1).Style.Font.Bold = true;
        //        oWs.Column(1).AutoFit();
        //        oWs.Column(2).AutoFit();
        //        oWs.Column(3).AutoFit();
        //        oWs.Column(4).AutoFit();
        //        oWs.Column(5).AutoFit();

        //        oEx.Save();
        //    }

        //    Response.ClearContent();
        //    Response.AddHeader("content-disposition", "attachment; filename=Cuenta_corriente.xls");
        //    Response.ContentType = "application/json";

        //    return Json(new { Archivo = _servidor });
        //    //return new ContentResult
        //    //{
        //    //    Content = "{ \"__a\": \"" + _servidor + "\" }",
        //    //    ContentType = "application/x-ms-excel"
        //    //};
        //}

        public ActionResult Descarga(string __a)
        {
            var grid = new System.Web.UI.WebControls.GridView();
            //var collection =  List<Observacion>(__a);
            var collection = new NObservacion().NLista();

            //var collection = CuentaCorrienteAD.Instancia.ListarAll("", 10);
            grid.DataSource = from d in collection
                              select new
            {
                ID           = d.obs_id,
                ABREVIATURA  = d.obs_abreviatura,
                DESCRIPCION  = d.obs_descripcion,
                GRUPO        = d.gde_descripcion,
                ESTADO       = (d.obs_estado == 2 ? "Inactivo" : "Activo"),
                PIDE_FOTO    = (d.obs_pideFoto == "2" ? "Inactivo" : "Activo"),
                NO_PIDE_FOTO = (d.obs_noPideFoto == "2" ? "Inactivo" : "Activo")
            };
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Observacion_Listado.xls");
            Response.ContentType = "application/x-ms-excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();

            return(null);
        }
예제 #9
0
        public ActionResult Index_Post(String lang, String excelCall)
        {
            if (!string.IsNullOrEmpty(lang))
            {
                if (HomeController.Language == "1")
                {
                    HomeController.Language = "2";
                    Session["Lang"]         = "Arabic";
                }
                else
                {
                    if (HomeController.Language == "2")
                    {
                        HomeController.Language = "1";
                        Session["Lang"]         = "English";
                    }
                }
            }

            if (!string.IsNullOrEmpty(excelCall))
            {
                var natTable = new System.Data.DataTable("teste");

                natTable.Columns.Add("المرجع", typeof(string));
                natTable.Columns.Add("الحالة", typeof(string));
                //natTable.Columns.Add("المجموعة", typeof(string));
                natTable.Columns.Add("التصنيف", typeof(string));
                //natTable.Columns.Add("رقم العداد", typeof(string));
                natTable.Columns.Add("الجنسية", typeof(string));
                natTable.Columns.Add("الرمز", typeof(string));
                var Lrecord = db.CR_Mas_Sup_Nationalities.ToList();
                if (Lrecord != null)
                {
                    foreach (var i in Lrecord)
                    {
                        natTable.Rows.Add(i.CR_Mas_Sup_Nationalities_Reasons, i.CR_Mas_Sup_Nationalities_Status,
                                          i.CR_Mas_Sup_Nationalities_Country_Code, i.CR_Mas_Sup_Nationalities_Ar_Name, i.CR_Mas_Sup_Nationalities_Code);
                    }
                }
                var grid = new System.Web.UI.WebControls.GridView();
                grid.DataSource = natTable;
                grid.DataBind();

                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
                Response.ContentType = "application/ms-excel";

                Response.Charset = "";
                StringWriter   sw  = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);

                grid.RenderControl(htw);

                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
            return(View(db.CR_Mas_Sup_Nationalities.ToList()));
        }
예제 #10
0
        public void ToExcel(HttpResponseBase Response, object clientsList)
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = clientsList;
            grid.DataBind();
            Response.ClearContent();

            //Response.AddHeader("content-disposition", "attachment; filename=Export.xls");
            //Response.ContentType = "application/excel";

            //Response.AddHeader("content-disposition", "attachment;filename=Lotes.xls");
            //Response.AddHeader("Content-Type", "application/vnd.ms-excel");

            //Response.AddHeader("content-disposition", "attachment; filename= LotesExcel.xlsx");
            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename= LotesTestes.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #11
0
        public ActionResult downloadweekly(DateTime DeliverTime, string restcode)
        {
            if (DeliverTime != null)
            {
                ViewBag.Message = "Your application description page.";
                Ankapurservices objCrd     = new Ankapurservices();
                var             modelCust1 = objCrd.Weeklyreports(DeliverTime, restcode);
                var             gv         = new System.Web.UI.WebControls.GridView();
                gv.DataSource = modelCust1;
                gv.DataBind();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=ankapurchickenweekly.xls");
                Response.ContentType = "application/ms-excel";
                Response.Charset     = "";
                StringWriter   objStringWriter   = new StringWriter();
                HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);

                gv.RenderControl(objHtmlTextWriter);
                Response.Output.Write(objStringWriter.ToString());

                Response.Flush();
                Response.End();
                return(RedirectToAction("Index", "dailyReport"));
            }


            return(Content("<script> alert('please select date')</script>"));
        }
        public void ExportBookedSeatsToExcel()
        {
            var seats = new System.Data.DataTable("bookers");

            seats.Columns.Add("Area", typeof(string));
            seats.Columns.Add("Name", typeof(string));
            seats.Columns.Add("Number", typeof(string));
            seats.Columns.Add("Seat", typeof(string));
            seats.Columns.Add("Price", typeof(string));
            seats.Columns.Add("Booked by", typeof(string));
            seats.Columns.Add("Booked at", typeof(DateTime));

            db.Seats.Where(s => s.Status == SeatStatus.Booked).ToList().ForEach(s =>
            {
                seats.Rows.Add(s.AreaDescriptionEn, s.RowNameEn, s.RowNumber, s.SeatNumber, s.Price,
                               s.BookedBy.LastName + " " + s.BookedBy.FirstName, s.BookedAt);
            });

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = seats;
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Seats.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #13
0
        public ActionResult Exports(string username, string time, string content, int?page)
        {
            var grid = new System.Web.UI.WebControls.GridView();
            int i    = 1;

            grid.DataSource = from item in GetCoaches(username, time, content, page)
                              select new
            {
                序号   = i++,
                记录人  = item.UserName,
                内容   = item.NoteContent,
                评论   = item.CommentContent,
                发布时间 = item.ReleaseTime
            };
            grid.DataBind();
            Response.ClearContent();
            string name = "记与思统计表" + DateTime.Now.ToString("yyyyMMddHHmmssffff");

            Response.AddHeader("content-disposition", "attachment; filename='" + name + "'.xls");
            Response.Buffer          = true;
            Response.Charset         = "UTF-8";
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType     = "application/ms-excel";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
            return(null);
        }
예제 #14
0
        public void DownloadExcelForSupplierLedger()
        {
            DataTable emps = TempData["Data"] as DataTable;
            var       grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = emps;
            grid.DataBind();
            Response.ClearContent();
            Response.Buffer  = true;
            Response.Charset = "";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            string filePath = Server.MapPath("~/SupplierLedgerXLSheet/" + 1 + "/generated/");

            bool isExists = System.IO.Directory.Exists(filePath);

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            string fileName = "SupplierLedgerReport" + ".xls";
            // Write the rendered content to a file.
            string renderedGridView = sw.ToString();

            System.IO.File.WriteAllText(filePath + fileName, renderedGridView);
        }
예제 #15
0
        public void ExportBookersToExcel()
        {
            var bookers = new System.Data.DataTable("bookers");

            bookers.Columns.Add("LastName", typeof(string));
            bookers.Columns.Add("FirstName", typeof(string));
            bookers.Columns.Add("Email", typeof(string));
            bookers.Columns.Add("Phone", typeof(string));
            bookers.Columns.Add("Booked seats", typeof(string));
            bookers.Columns.Add("Inviting company", typeof(string));
            bookers.Columns.Add("After party", typeof(string));

            var bookerList = GetBookersAndSeats();

            bookerList.ForEach(b =>
            {
                bookers.Rows.Add(b.LastName, b.FirstName, b.Email, b.PhoneNumber, String.Join(" ", b.Seats), b.Face, (b.Party ?? false) ? "After party" : "");
            });

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = bookers;
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Bookers.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #16
0
        /// <summary>
        /// Autor: jlucero
        /// Fecha: 2015-06-16
        /// </summary>
        /// <param name="__a"></param>
        /// <returns></returns>

        public ActionResult Descarga()
        {
            var grid       = new System.Web.UI.WebControls.GridView();
            var collection = new NServicio().NLista();

            grid.DataSource = from d in collection
                              select new
            {
                ID          = d.ser_id,
                DESCRIPCION = d.ser_descripcion,
                ESTADO      = (d.ser_estado == 2 ? "Inactivo" : "Activo")
            };
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Servicio_Listado.xls");
            Response.ContentType = "application/x-ms-excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();

            return(null);
        }
예제 #17
0
        public void ExportToCSV()
        {
            var sb   = new StringBuilder();
            var data = from t in db.Tools
                       select new
            {
                t.toolID,
                t.toolName,
                t.toolBrand,
                t.toolNotes,
                t.toolAvailable            //needs to be t.toolAvailable where t.toolAvailable
            };

            var list = data.ToList();
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = list;
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Items.xls");
            Response.ContentType = "application/vnd.ms-excel";

            StringWriter sw = new StringWriter();

            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #18
0
        /// <summary>
        /// Consultar nota
        /// </summary>
        /// <param name="Codigo"></param>
        /// <returns></returns>
        public ActionResult DetalharNota(int Codigo)
        {
            NotaFiscal nota = NotaFiscalNeg.Buscar(Codigo);

            List <ListaProdutoAux> itens = new List <ListaProdutoAux>();

            foreach (Item item in nota.Itens)
            {
                itens.Add(new ListaProdutoAux()
                {
                    Nome = item.Produto.Nome, Quantidade = item.Quantidade, Preco = item.Produto.Preco
                });
            }

            System.Web.UI.WebControls.GridView gView = new System.Web.UI.WebControls.GridView();
            gView.DataSource = itens;
            gView.DataBind();
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))
                {
                    gView.RenderControl(htw);
                    ViewBag.GridViewString = sw.ToString();
                }
            }
            return(View(nota));
        }
예제 #19
0
        /// <summary>
        /// 将DataTable数据导出到EXCEL,调用该方法后自动返回可下载的文件流
        /// </summary>
        /// <param name="dtData">要导出的数据源</param>
        public static void DataTable1Excel(System.Data.DataTable dtData)
        {
            System.Web.UI.WebControls.GridView gvExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType     = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                curContext.Response.Charset         = "utf-8";

                // 导出excel文件
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                // 为了解决gvData中可能进行了分页的情况,需要重新定义一个无分页的GridView
                gvExport             = new System.Web.UI.WebControls.GridView();
                gvExport.DataSource  = dtData.DefaultView;
                gvExport.AllowPaging = false;
                gvExport.DataBind();

                // 返回客户端
                gvExport.RenderControl(htmlWriter);
                curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />" + strWriter.ToString());
                curContext.Response.End();
            }
        }
예제 #20
0
        public ActionResult ExportToExcel()
        {
            List <Employee_Master> emplist = new List <Employee_Master>();

            emplist = db.Employee_Master.ToList();

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = from p in emplist
                              select new
            {
                Name    = p.Name.ToString(),
                Dob     = p.Date_Of_Birth.ToString(),
                Country = p.Country_Info.Country_name.ToString(),
                City    = p.City_Info.City_Name.ToString(),
                State   = p.State_info.State_Name.ToString(),
                EmailId = p.EmailId.ToString(),
                Phone   = p.Phone.ToString()
            };
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=MyFile.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw = new StringWriter();
            HtmlTextWriter tw = new HtmlTextWriter(sw);

            grid.RenderControl(tw);
            Response.Write(sw.ToString());
            Response.End();
            return(Json("Success"));
        }
예제 #21
0
        //public JsonResult UploadMedia(AcademicProfileVM academic)
        //{
        //    var file = academic.ImageFile;
        //    if (file != null)
        //    {
        //        var fileName = Path.GetFileName(file.FileName);
        //        var extension = Path.GetExtension(file.FileName);
        //        var FileNameWithourExt = Path.GetFileNameWithoutExtension(file.FileName);
        //        file.SaveAs(Server.MapPath("/Uploads/" + file.FileName));
        //    }
        //    return Json(file.FileName, JsonRequestBehavior.AllowGet);
        //}
        public void ExportClientsListToExcel()
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = /*from d in dbContext.diners
                               * where d.user_diners.All(m => m.user_id == userID) && d.active == true */
                              from d in EmpRep.GetAll()
                              select new
            {
                Name = d.Name,
                Age  = d.Age,
                //Department = d.Department,
                Designation = d.Designation
            };

            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Exported_Diners.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #22
0
        public ActionResult ExportData(DateTime?from, DateTime?to)
        {
            if (!from.HasValue)
            {
                from = new DateTime(2015, 1, 1);
            }
            if (!to.HasValue)
            {
                to = DateTime.Now;
            }
            var gv = new System.Web.UI.WebControls.GridView();

            gv.DataSource = _videoRepository.GetAccessDataBetween(from.Value, to.Value);
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=VITV_" + from.Value.ToShortDateString() + "_" + to.Value.ToShortDateString() + ".xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset     = "";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
            return(RedirectToAction("Index"));
        }
예제 #23
0
        public ActionResult ExportExcel_EmployeeData()
        {
            var odb  = new testEntities2();
            var sb   = new StringBuilder();
            var data = from s in odb.ProductDetails // Odb is the object of edmx file
                       select new
            {
                // You can choose column name according your need

                s.Product_id,
                s.Email,
                s.Product_name,
                s.Product_type,
                s.Product_weight,
                s.Product_price,
                s.Product_description,
            };
            var list = data.ToList();
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = list;
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Product_list.xls");
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();

            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return(View());
        }
예제 #24
0
        public ActionResult ExportToExcel()
        {
            var gv = new System.Web.UI.WebControls.GridView();

            gv.DataSource = db.Contacts
                            //.Where(p => p.state_contact == "1")
                            .Select(r => new {
                Names   = r.name_contact,
                Emails  = r.email_contact,
                Date    = r.date_contact,
                Subject = r.subject_contact
            })
                            .OrderByDescending(p => p.Date)
                            .ToList();
            gv.DataBind();
            Response.Clear();
            Response.Buffer = true;
            //Response.AddHeader("content-disposition",
            // "attachment;filename=GridViewExport.xls");
            Response.Charset     = "utf-8";
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            //Mã hóa chữa sang UTF8
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

            System.IO.StringWriter       sw = new StringWriter();
            System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

            if (gv.Rows.Count > 0)
            {
                for (int i = 0; i < gv.Rows.Count; i++)
                {
                    //Apply text style to each Row
                    gv.Rows[i].Attributes.Add("class", "textmode");
                }


                //Add màu nền cho header của file excel
                gv.HeaderRow.BackColor = System.Drawing.Color.DarkBlue;
                //Màu chữ cho header của file excel
                gv.HeaderStyle.ForeColor = System.Drawing.Color.White;

                gv.HeaderRow.Cells[0].Text = "Họ Tên";
                gv.HeaderRow.Cells[1].Text = "Email";
                gv.HeaderRow.Cells[2].Text = "Ngày nhận";
                gv.HeaderRow.Cells[3].Text = "Nội dung";
                gv.RenderControl(hw);

                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
                var model = db.Contacts
                            .OrderByDescending(p => p.date_contact)
                            .ToList();
                return(View("View", model));
            }
            Response.Write("<script>alert('Danh sách hiện đang trống!');</script>");
            return(View());
        }
        public void ExportTrackBookingReportToExcel()
        {
            var grid = new System.Web.UI.WebControls.GridView();

            if (Session["TRACKBOOKINGS"] != null)
            {
                var resp = (List <BookingReporting>)Session["TRACKBOOKINGS"];
                grid.DataSource = from r in resp
                                  select new
                {
                    QuotationNo   = r.QuotationNumber,
                    InvoiceNo     = r.InvoiceNumber,
                    Organiser     = r.OrganiserName,
                    Company       = r.CompanyName,
                    QuotationDate = r.QuotationDate.Value.ToString("dd-MMMM-yyyy"),
                    InvoicedDate  = r.InvoiceDate.Value.ToString("dd-MMMM-yyyy"),
                    InvoiceTotal  = r.InvoiceTotal,
                    BusType       = r.BusType,
                    FleetNo       = r.FleetNumber
                };
            }

            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=TrackBooking_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
        }
예제 #26
0
        public void ExportToExcel()
        {
            using (var mycontext = new xyzEntities())
            {
                var grid = new System.Web.UI.WebControls.GridView();

                grid.DataSource = from d in mycontext.Customers
                                  select new
                {
                    Address     = d.Address,
                    CompanyName = d.CompanyName,
                    Country     = d.Country,
                    ContactName = d.ContactName
                };

                grid.DataBind();

                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=Exported_Diners.xls");
                Response.ContentType = "application/excel";
                StringWriter   sw  = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);

                grid.RenderControl(htw);

                Response.Write(sw.ToString());

                Response.End();
            }
        }
        public ActionResult ReadOfx()
        {
            String         parametro = "";
            bool           primeiro  = false;
            List <ofxData> lista     = new List <ofxData>();

            if (HttpContext.Request.Files.Count > 0)
            {
                var docfiles = new List <string>();
                foreach (string file in HttpContext.Request.Files)
                {
                    var postedFile = HttpContext.Request.Files[file];

                    if (!postedFile.FileName.Contains(".ofx") && postedFile.FileName != "")
                    {
                        return(RedirectToAction("Error"));
                    }
                    if (postedFile.FileName == "")
                    {
                        if (primeiro)
                        {
                            return(RedirectToAction("Error"));
                        }

                        primeiro = true;
                    }

                    byte[] bytes;
                    using (var stream = new MemoryStream())
                    {
                        postedFile.InputStream.CopyTo(stream);
                        bytes = stream.ToArray();
                    }

                    NiboChallenge.Util.NiboChallenge nibo = new NiboChallenge.Util.NiboChallenge();
                    nibo.ReadOfx(bytes, lista);
                }

                System.Web.UI.WebControls.GridView gView = new System.Web.UI.WebControls.GridView();
                gView.DataSource = lista.ToList();
                gView.DataBind();
                using (System.IO.StringWriter sw = new System.IO.StringWriter())
                {
                    using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))
                    {
                        gView.RenderControl(htw);
                        ViewBag.GridViewString = sw.ToString();
                        ViewBag.totalItens     = lista.Count();
                    }
                }
                return(View());
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
예제 #28
0
        /// <summary>
        /// Exports the Data of Referals to the Excel between the Selected Dates. Default will be all,incase no date selected.
        /// </summary>
        /// <param name="objdata"></param>
        /// <returns></returns>
        public ActionResult ExportToExcell(AgentReferences objdata)
        {
            var objData = GetAllReferals(objdata.FromDate != null ? Convert.ToDateTime(objdata.FromDate): (DateTime?)null,
                                         objdata.ToDate != null ? Convert.ToDateTime(objdata.ToDate) : (DateTime?)null);

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));
            dt.Columns.Add("ReferedBy", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("Phone", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("State", typeof(string));
            dt.Columns.Add("Status", typeof(string));

            foreach (var item in objData)
            {
                var rec = dt.NewRow();
                rec["FirstName"] = item.FirstName;
                rec["LastName"]  = item.LastName;
                rec["ReferedBy"] = item.Name;
                rec["Email"]     = item.Email;
                rec["Phone"]     = item.Phone.ToString();
                rec["Address"]   = item.Address;
                rec["State"]     = item.State;
                rec["Status"]    = item.Status;
                dt.Rows.Add(rec);
            }

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = dt;
            grid.DataBind();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            Response.ContentType = "application/ms-excel";

            Response.Charset = "";
            StringWriter sw = new StringWriter();

            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Clear();
            Response.End();

            return(RedirectToAction("Referals"));
        }
예제 #29
0
        public static byte[] ToBytes(this System.Data.DataTable data)
        {
            System.Web.UI.WebControls.GridView grid = new System.Web.UI.WebControls.GridView();
            grid.DataSource = data;
            grid.DataBind();

            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            return(Encoding.ASCII.GetBytes(sw.ToString()));
        }
        public void ExportToExcel(string filterNroEmpleado, string filterNombre, string filterApellidos, string filterCategoria, string filterLinea,
                                  string filterCelda, string filterFechaLiberacion, string filterTipoTecnologiaId, string filterCentro, string filterSinNecesidadAsignada, string filterNivelIdioma)
        {
            IDictionary <string, string> CustomFilters = new Dictionary <string, string> {
                { "NroEmpleado", filterNroEmpleado },
                { "Nombre", filterNombre },
                { "Apellidos", filterApellidos },
                { "Categoria", filterCategoria },
                { "Linea", filterLinea },
                { "Celda", filterCelda },
                { "FechaLiberacion", filterFechaLiberacion },
                { "TipoTecnologiaId", filterTipoTecnologiaId },
                { "CentroSearch", filterCentro },
                { "SinNecesidadAsignada", filterSinNecesidadAsignada },
                { "NivelIdioma", filterNivelIdioma }
            };

            //filtro por el centro
            if (HttpContext.Session["Usuario"] != null)
            {
                var UsuarioRolPermisoViewModel = (UsuarioRolPermisoViewModel)HttpContext.Session["Usuario"];
                if (UsuarioRolPermisoViewModel.CentroIdUsuario != null)
                {
                    CustomFilters.Add("Centro", HttpContext.Session["CentroIdUsuario"].ToString());
                }
            }

            var request = new DataTableRequest();

            request.CustomFilters = CustomFilters;
            var response = _PersonaLibreService.GetPersonasLibresExportToExcel(request);



            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = response.PersonaLibreRowExportToExcelViewModel;
            grid.DataBind();
            Response.ClearContent();
            string filename = string.Format("Listado_de_PersonasLibres_{0}", DateTime.Now.ToShortDateString() + ".xls");

            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename));
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #31
0
        /// <summary>
        /// Submit the Request to Fetch Data For Excel.
        /// </summary>  
    
        public ActionResult ExportToExcel()
        {
            dynamic objAcccount;
            using (var db = new CSN.DAL.CSNDBEntities())
            {
                objAcccount = (from x in db.TblAccountLists.OrderBy(e => e.Company)
                               join y in db.TblCSNLists on x.CSNDirID equals y.CSNID 
                               select new
                               {
                                   Company = x.Company,
                                   Address = x.Address1 + " " + x.Address2 + " " + x.City,
                                   CompanyPhone = x.CompanyPhone,
                                   CompanyFax = x.CompanyFax,
                                   State = x.State,
                                   Zip = x.Zip,
                                   Country = x.Country,
                                   ShippingAddress = x.ShipToAddress1 + " " + x.ShipToAddress2 + " " + x.ShipToCity,
                                   CSNRef = y.FullName,
                                   AccountType = x.CustType1,
                                   NumberOfStore = x.NumStores
                               }).ToList();


            }

            var grid = new System.Web.UI.WebControls.GridView();

            grid.AutoGenerateColumns = true;
            grid.AllowPaging = false;

            grid.DataSource = objAcccount;
            grid.DataBind();
            grid.HeaderStyle.BackColor = System.Drawing.Color.FromName("#fff8cf");
            grid.HeaderStyle.Font.Bold = true;

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            grid.RenderControl(oHtmlTextWriter);

            ShowXLS(oStringWriter.ToString(), "AccountList");
            return null;
        }
예제 #32
0
        public ActionResult xls()
        {
            using (ESKAPEDEContext db = new ESKAPEDEContext())
            {
                IQueryable<vwRequest> results = db.vwRequests;

                System.Web.UI.WebControls.GridView grd = new System.Web.UI.WebControls.GridView();
                grd.DataSource = db.vwRequests.ToList();
                grd.DataBind();

                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=ReportSKPD.xls");
                Response.ContentType = "application/ms-excel";

                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);

                // Render the grid contents => the writer objects => Response object
                grd.RenderControl(htw);
                Response.Write(sw.ToString());

                Response.End();
                return View("Index");
            }
        }
        public void ExportSubjectListToExcel(int id)
        {
            GradeStudentsGradesVM model = new GradeStudentsGradesVM();
            GradeRepository gradeRepo = new GradeRepository();
            SubjectRepository subjRepo = new SubjectRepository();
            UserRepository<Student> studentRepo = new UserRepository<Student>();

            List<Student> students = studentRepo.GetAll(filter: s => s.Course.CourseSubject.Any(t => t.SubjectID == id));
            List<Grade> grades = gradeRepo.GetAll(filter: s => s.SubjectID == id);

            Subject subject = subjRepo.GetByID(id);

            var grid = new System.Web.UI.WebControls.GridView();

            var products = new System.Data.DataTable(subject.Name);

            products.Columns.Add("FacultiNumber", typeof(string));
            products.Columns.Add("FirstName", typeof(string));
            products.Columns.Add("LastName", typeof(string));
            products.Columns.Add("Grade", typeof(string));
            foreach (var student in students)
            {
                string grade = student.Grades.Select(x => x.GradeValue).FirstOrDefault().ToString();
                grade = grade == "0" ? "" : grade;
                products.Rows.Add(student.FacultiNumber, student.FirstName, student.LastName, grade);
            }

            grid.DataSource = products;
            // grid.DataSource = model.Students;

            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + subject.Name + ".xlsx");
            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
        }
예제 #34
0
        /// <summary>
        /// 将Datatable转换为Excel
        /// </summary>
        /// <param name="dtData"></param>
        /// <param name="FileName"></param>
        public static void DataTableToExcel(System.Data.DataTable dtData, String FileName)
        {
            if (dtData == null || dtData.Rows.Count == 0)
            {
                return;
            }
            System.Web.UI.WebControls.GridView dgExport = null;
            //当前对话 
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            //IO用于导出并返回excel文件 
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                //设置编码和附件格式 
                //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
                curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                curContext.Response.ContentType = "application nd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;//.GetEncoding("GB2312");
                curContext.Response.Charset = "UTF-8";// "GB2312";

                //导出Excel文件 
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView 
                dgExport = new System.Web.UI.WebControls.GridView();
                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                //下载到客户端 
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
        public ActionResult Export()
        {
            var grid = new System.Web.UI.WebControls.GridView
            {
                DataSource = this.volunteerRepository.All.ToList()
            };

            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=KiyvSmartCity_Volunteers.xls");
            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());

            Response.End();
            return null;
        }
예제 #36
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpContext curContext = HttpContext.Current;
            curContext.Response.Clear();
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + this.FileName);
            curContext.Response.Charset = "";
            curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            curContext.Response.ContentType = "application/ms-word";

            HttpWebRequest wreq = (HttpWebRequest)HttpWebRequest.Create(this.Url);
            HttpWebResponse wres = (HttpWebResponse)wreq.GetResponse();
            Stream s = wres.GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.ASCII);

            curContext.Response.Write(sr.ReadToEnd());
            curContext.Response.End();

            //Bind the Data to Asp.Net DataGrid - you can still use this in Asp.Net MVC though it
            //cannot be used in the .aspx View
            System.Web.UI.WebControls.GridView grd = new System.Web.UI.WebControls.GridView();
            grd.DataSource = this.Data;
            grd.DataBind();
            HttpContext.Current.Response.ClearContent();
            bool exportReady = false;
            switch (ExportType) {
                case Models.Admin.Enums.ExportType.Word:
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=DealReport.doc");
                    HttpContext.Current.Response.ContentType = "application/ms-word";
                    exportReady = true;
                    break;
                case Models.Admin.Enums.ExportType.Excel:
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=DealReport.xls");
                    HttpContext.Current.Response.ContentType = "application/excel";
                    exportReady = true;
                    break;
            }
            if (exportReady) {
                StringWriter swr = new StringWriter();
                HtmlTextWriter tw = new HtmlTextWriter(swr);
                grd.RenderControl(tw);
                HttpContext.Current.Response.Write(swr.ToString());
                HttpContext.Current.Response.End();
            }
        }
        public void ExportSubjectListToExcel(int id)
        {
            StudentIndexVM model = new StudentIndexVM();
            GradeRepository gradeRepo = new GradeRepository();
            UserRepository<Student> studentRepo = new UserRepository<Student>();
            Student student = studentRepo.GetByID(id);

            model.Grades = gradeRepo.GetAll(filter: s => s.StudentID == id);

            var grid = new System.Web.UI.WebControls.GridView();

            var products = new System.Data.DataTable(student.FirstName);

            products.Columns.Add("Subject", typeof(string));
            products.Columns.Add("Grade", typeof(string));

            foreach (var item in model.Grades)
            {
                products.Rows.Add(item.Subject.Name, item.GradeValue);
            }

            grid.DataSource = products;
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + student.FacultiNumber + ".xls");
            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #38
0
        public void ExportarExcel()
        {
            var visitas = (from v in db.Local_Visitas_Agentes
                           select v).ToList();

            //transformando
            foreach (var v in visitas)
            {
                v.banner = (v.BannerVisible == 1) ? v.banner = "SI" : (v.BannerVisible == 0) ? v.banner = "NO" : v.banner = "N/A";
                v.saliente = (v.SalienteVisible == 1) ? v.saliente = "SI" : (v.SalienteVisible == 0) ? v.saliente = "NO" : v.saliente = "N/A";
                v.totem = (v.TotemVisible == 1) ? v.totem = "SI" : (v.TotemVisible == 0) ? v.totem = "NO" : v.totem = "N/A";
                v.cover = (v.CoverVisible == 1) ? v.cover = "SI" : (v.CoverVisible == 0) ? v.cover = "NO" : v.cover = "N/A";
                v.portaafiche = (v.PortaAficheVisible == 1) ? v.portaafiche = "SI" : (v.PortaAficheVisible == 0) ? v.portaafiche = "NO" : v.portaafiche = "N/A";
                v.colgante = (v.ColganteVisible == 1) ? v.colgante = "SI" : (v.ColganteVisible == 0) ? v.colgante = "NO" : v.colgante = "N/A";
                v.flyers = (v.FlyersVisibles == 1) ? v.flyers = "SI" : (v.FlyersVisibles == 0) ? v.flyers = "NO" : v.flyers = "N/A";
                v.fechaCorta = v.Fecha.ToShortDateString();
            }

            //filtrando
            var visits = from v in visitas
                         join a in db.Agencias on v.Numero_Agencia equals a.NUMERO_AGENCIA
                         join ag in db.VAgencias on v.Numero_Agencia equals ag.NUMERO_AGENCIA
                         select new { v.id, v.Numero_Agencia, ag.RAZON_SOCIAL, v.Local_FMR.nombre, v.fechaCorta, v.Hora, v.banner, v.saliente, v.totem, v.cover, v.portaafiche, v.colgante, v.flyers, v.comentarios };

            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = visits;

            grid.DataBind();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=visitas.xls");
            Response.ContentType = "application/ms-excel";

            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();

            Response.End();
        }