public void ExportToCSV() { StringWriter sw = new StringWriter(); sw.WriteLine("\"Id\",\"Text\",\"CityId\",\"DistrictId\",\"Status\",\"NeighborId\",\"ListWard\",\"ListUser\""); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment;filename=Regions.csv"); Response.ContentType = "application/ms-excel"; Response.ContentEncoding = System.Text.Encoding.Unicode; Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); Response.Charset = "UTF-8"; var lstRegion = regionService.List(); // Convert data to table. List <Models.RegionExcel> lstRegionExcel = new List <Models.RegionExcel>(); Models.RegionExcel r = new Models.RegionExcel(); string delimiter = ","; foreach (var region in lstRegion) { r = new Models.RegionExcel() { Id = region.Id, CityId = region.CityId, DistrictId = region.DistrictId, Text = region.Text, NeighborId = region.NeighborId != null ? region.NeighborId.Value : 0, Status = region.Status ? 1 : 0, ListWard = string.Join(delimiter, region.ListWard.Select(x => x.Id)), ListUser = string.Join(delimiter, region.ListUser.Select(x => x.Id)) }; lstRegionExcel.Add(r); } foreach (var region in lstRegionExcel) { sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"", region.Id, region.Text, region.CityId, region.DistrictId, region.Status, region.NeighborId, region.ListWard, region.ListUser )); } Response.Write(sw.ToString()); Response.End(); }
public void ExportToExcel() { var lstRegion = regionService.List(); // Convert data to table. List <Models.RegionExcel> lstRegionExcel = new List <Models.RegionExcel>(); Models.RegionExcel r = new Models.RegionExcel(); string delimiter = ","; foreach (var region in lstRegion) { r = new Models.RegionExcel() { Id = region.Id, CityId = region.CityId, DistrictId = region.DistrictId, Text = region.Text, NeighborId = region.NeighborId != null ? region.NeighborId.Value : 0, Status = region.Status?1:0, ListWard = string.Join(delimiter, region.ListWard.Select(x => x.Id)), ListUser = string.Join(delimiter, region.ListUser.Select(x => x.Id)) }; lstRegionExcel.Add(r); } var grid = new GridView(); grid.DataSource = lstRegionExcel; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=Regions.xls"); Response.Charset = "UTF-8"; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); htw.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); grid.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); }