//留言的导出 protected void btnOut_Click(object sender, EventArgs e) { System.Web.UI.WebControls.DataGrid dgExport = null; // 当前对话 System.Web.HttpContext curContext = System.Web.HttpContext.Current; // IO用于导出并返回excel文件 System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; // 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = ""; // 导出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); dgExport = new System.Web.UI.WebControls.DataGrid(); string filename = "leaveMsgReceive"; dgExport.DataSource = outDataTable; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); }
/// <summary> /// 导出excel /// </summary> /// <param name="ds"></param> /// <param name="FileName"></param> public void CreateExcel(DataSet ds, string FileName) { System.Web.UI.WebControls.DataGrid dgExport = null; System.Web.HttpContext curContext = System.Web.HttpContext.Current; System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (ds != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "UTF-8"; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(FileName)) + ".xls"); strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = ds.Tables[0].DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } }
public static void Convert(System.Data.DataSet ds, string TableName, System.Web.HttpResponse response, string ExcelName) { //let's make sure the table name exists //if it does not then call the default method if (ds.Tables[TableName] == null) { Convert(ds, response, ExcelName); } //we've got a good table so //let's clean up the response.object response.Clear(); response.Charset = ""; //set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; //create a string writer System.IO.StringWriter stringWrite = new System.IO.StringWriter(); //create an htmltextwriter which uses the stringwriter System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); //instantiate a datagrid System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); //set the datagrid datasource to the dataset passed in dg.DataSource = ds.Tables[TableName]; //bind the datagrid dg.DataBind(); //tell the datagrid to render itself to our htmltextwriter dg.RenderControl(htmlWrite); //all that's left is to output the html response.Write(stringWrite.ToString()); response.End(); }
/// <summary> /// Exporta la información a Excel. /// </summary> /// <param name="response">HttpResponse actual.</param> /// <param name="data">Datos a exportar.</param> /// <param name="nombreArchivo">Nombre del archivo Excel</param> public static void ExportToExcelFile(HttpResponse response, DataView data, string nombreArchivo) { var dg = new DataGrid { DataSource = data }; dg.DataBind(); response.Clear(); response.Buffer = true; //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet response.AddHeader("Content-Disposition", "filename=" + nombreArchivo); response.ContentType = "application/vnd.ms-excel"; response.Charset = "UTF-8"; response.ContentEncoding = System.Text.Encoding.Default; var stringWriter = new StringWriter(); var htmlWriter = new HtmlTextWriter(stringWriter); dg.RenderControl(htmlWriter); response.Write(stringWriter.ToString()); //resp.Flush(); try { response.End(); } catch (Exception ex) { ISException.RegisterExcepcion(ex); throw ex; } }
public void ExportToExcel(DataTable dt) { if (dt.Rows.Count > 0) { string filename = "Test1234.xls"; string excelHeader = "Quiz Report"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); DataGrid dgGrid = new DataGrid(); dgGrid.DataSource = dt; dgGrid.DataBind(); // Report Header hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>"); //Get the HTML for the control. dgGrid.RenderControl(hw); //Write the HTML back to the browser. Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ""); this.EnableViewState = false; Response.Write(tw.ToString()); Response.End(); } }
private void UploadDataTableToExcel(DataTable feedBacks) { HttpResponse response = HttpContext.Current.Response; try { response.Clear(); response.Charset = string.Empty; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=\"FeedBack.xls\""); using (StringWriter stringWriter = new StringWriter()) { using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter)) { DataGrid dataGrid = new DataGrid(); dataGrid.DataSource = feedBacks; dataGrid.DataBind(); dataGrid.RenderControl(htmlTextWriter); response.Write(stringWriter.ToString()); } } response.End(); } catch (ThreadAbortException ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } }
protected void Page_Load(object sender, EventArgs e) { //if (Session["Type"].ToString() == "Excel") //{ DataSet ds = Session["ExcelDs"] as DataSet; Response.Clear(); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=ExcelName.xls"); System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = ds.Tables[0]; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); //} //else //{ // Response.ContentType = "application/pdf"; // string path = Server.MapPath("~/PDFS/TestM10.pdf"); // byte[] bts = System.IO.File.ReadAllBytes(path); // Response.Clear(); // Response.ClearHeaders(); // Response.AddHeader("Content-Type", "Application/octet-stream");//octet-stream // Response.AddHeader("Content-Length", bts.Length.ToString()); // Response.AddHeader("Content-Disposition", "attachment; filename=1.pdf"); // Response.BinaryWrite(bts); // Response.Flush(); // Response.TransmitFile(path); // Response.End(); //} }
public static void ConfigureDataGrid(ref DataGrid dgResults, DataTable dt, bool showColumnHeadings, bool useAlternatingRowColor, bool showGridLines, Int16 cellPadding, string columnLabels) { dgResults.ShowHeader = showColumnHeadings; dgResults.AlternatingItemStyle.BackColor = useAlternatingRowColor ? dgResults.BorderColor : dgResults.BackColor; if (showGridLines) { dgResults.GridLines = GridLines.Both; dgResults.BorderStyle = BorderStyle.Solid; } else { dgResults.GridLines = GridLines.None; dgResults.BorderStyle = BorderStyle.None; } dgResults.CellPadding = cellPadding; if (showColumnHeadings) { String[] strColumnLabel = columnLabels.Split(','); for (var i = 0; i < dt.Columns.Count; i++) { try { dt.Columns[i].ColumnName = strColumnLabel[i].Trim(); } catch { } } } }
protected void lnkExportToExcel_Click(object sender, EventArgs e) { try { DataTable dtb = new DataTable(); dtb = sitesListBAL.GetSitesListForExportToExcel(); string exportedFileName = "Sites_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; Response.Clear(); Response.Charset = ""; Response.ContentType = "application/ms-excel"; Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", exportedFileName)); System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.AllowPaging = false; dg.HeaderStyle.BackColor = System.Drawing.Color.RoyalBlue; dg.HeaderStyle.ForeColor = System.Drawing.Color.White; dg.DataSource = dtb; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } catch (Exception exp) { logExcpUIobj.MethodName = "lnkExportToExcel_Click()"; logExcpUIobj.ResourceName = "System_Settings_SitesList.CS"; logExcpUIobj.RecordId = "Export To excel"; logExcpUIobj.ExceptionDetails = "Error Occured. System Generated Error is: " + exp.ToString(); logExcpDALobj.SaveExceptionToDB(logExcpUIobj); log.Error("[System_Settings_SitesList : lnkExportToExcel_Click] An error occured in the processing of Records. Details : [" + exp.ToString() + "]"); } }
/// <summary> /// Gerar um arquivo apartir de um datatable /// </summary> /// <param name="data">Dados</param> /// <param name="nomeArquivo">Nome do arquivo</param> /// <returns>Caminho do arquivo</returns> private string SalvarExcel(DataTable data, string nomeArquivo) { // create the DataGrid and perform the databinding System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid(); grid.HeaderStyle.Font.Bold = true; grid.DataSource = data; grid.DataMember = data.TableName; grid.ItemDataBound += Item_Bound; grid.DataBind(); var extencaoArquivo = Path.GetExtension(nomeArquivo); var novoNome = Path.Combine(Server.MapPath("~/Download/")) + nomeArquivo.Remove((nomeArquivo.Length - extencaoArquivo.Length) - 1, extencaoArquivo.Length + 1); novoNome += HttpContext.Session.SessionID + ".xls"; // render the DataGrid control to a file var path = Path.Combine(Server.MapPath("~/Download/"), novoNome); using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { grid.RenderControl(hw); } } return(novoNome); }
private static void EportAllDataToExcel(DataTable dt) { System.Web.UI.WebControls.DataGrid dgExport = null; System.Web.HttpContext curContext = System.Web.HttpContext.Current; System.IO.StringWriter strWrite = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (dt.Rows.Count > 0) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "utf-8"; curContext.Response.AddHeader("Content-Disposition", "attachment;filename=1.xls"); strWrite = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWrite); dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dt.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWrite); curContext.Response.Flush(); curContext.Response.End(); } }
public static void ToExcelG(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head, string Foot)//add by zachary 2009-04-07 { System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); ToExcelFrontDecorator(hw); if (Title != "") { hw.Write(Title + "<br>"); } if (Head != "") { hw.Write(Head); } DataGrid2Excel.EnableViewState = false; DataGrid2Excel.RenderControl(hw); if (Foot != "") { hw.Write(Foot + "<br>"); } ToExelRearDecorator(hw); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.Buffer = true; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName) + ".xls"); response.Charset = "UTF-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.Write(sw.ToString()); response.End(); }
public static void ToExcelD(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head, string foot) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls"); //filename=Report.xls HttpContext.Current.Response.Charset = "UTF-8"; //UTF-8 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //msword;image/JPEG;text/HTML;image/GIF;vnd.ms-excel //HttpContext.Current.Application.Page.EnableViewState = false; //Turn off the view state. System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); hw.WriteLine(@"<HTML>"); hw.WriteLine(@"<BODY>"); hw.WriteLine("<b>" + Title + "</b>"); //string Head = @"<table border=1><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>"; if (Head != "") { hw.WriteLine(Head); } DataGrid2Excel.RenderControl(hw); //Get the HTML for the control. if (foot != "") { hw.WriteLine(foot); } hw.WriteLine(@"</BODY>"); hw.WriteLine(@"</HTML>"); hw.Flush(); hw.Close(); HttpContext.Current.Response.Write(tw.ToString()); //Write the HTML back to the browser. HttpContext.Current.Response.End(); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; var dg = new DataGrid(); string filename = null; switch (type) { case "donorfundtotals": filename = "DonorFundTotals"; dg.DataSource = ExportPeople.ExcelDonorFundTotals(Dt1, Dt2, fundid, campusid, pledges, nontaxdeductible, IncUnclosedBundles); break; case "donortotals": filename = "DonorTotals"; dg.DataSource = ExportPeople.ExcelDonorTotals(Dt1, Dt2, campusid, pledges, nontaxdeductible, IncUnclosedBundles); break; case "donordetails": filename = "DonorDetails"; dg.DataSource = ExportPeople.DonorDetails(Dt1, Dt2, fundid, campusid, pledges, nontaxdeductible, IncUnclosedBundles); break; } dg.DataBind(); Response.AddHeader("Content-Disposition", "attachment;filename={0}.xls".Fmt(filename)); dg.RenderControl(new HtmlTextWriter(Response.Output)); }
private void save(DataTable dt,string filename) { DataGrid excel = new DataGrid(); System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle(); System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle(); System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle(); AlternatingStyle.BackColor = System.Drawing.Color.LightGray; headerStyle.BackColor = System.Drawing.Color.LightGray; headerStyle.Font.Bold = true; headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; ; excel.AlternatingItemStyle.MergeWith(AlternatingStyle); excel.HeaderStyle.MergeWith(headerStyle); excel.ItemStyle.MergeWith(itemStyle); excel.GridLines = GridLines.Both; excel.HeaderStyle.Font.Bold = true; DataSet ds = new DataSet(); ds.Tables.Add(dt); excel.DataSource = ds; //输出DataTable的内容 excel.DataBind(); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); excel.RenderControl(oHtmlTextWriter); Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls"); Response.ContentType = "application/ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.Write(oHtmlTextWriter.InnerWriter.ToString()); Response.End(); }
private DataGridItem GetFooter(DataGrid grid) { Control table = grid.Controls[0]; DataGridItem footer = table.Controls[table.Controls.Count-1] as DataGridItem; if(footer.ItemType==ListItemType.Footer) return footer; return null; }
protected override void SaveComponent() { System.Web.UI.WebControls.DataGrid baseControl = (System.Web.UI.WebControls.DataGrid)base.GetBaseControl(); baseControl.ShowHeader = this.showHeaderCheck.Checked; baseControl.ShowFooter = this.showFooterCheck.Checked; baseControl.AllowSorting = this.allowSortingCheck.Checked; }
public void ToExcel(DataTable dt, string FileName, string Title, string Head) { System.Web.UI.WebControls.DataGrid dgTemp = new System.Web.UI.WebControls.DataGrid(); dgTemp.DataSource = dt; dgTemp.DataBind(); ToExcel(dgTemp, FileName, Title, Head); }
public void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head) { System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); FrontDecorator(hw); if (Title != "") { hw.Write(Title + "<br>"); } if (Head != "") { hw.Write(Head + "<br>"); } DataGrid2Excel.EnableViewState = false; DataGrid2Excel.RenderControl(hw); RearDecorator(hw); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.Buffer = true; response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); response.ContentType = "application/vnd.ms-excel"; response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>"); string file = HttpUtility.UrlEncode(FileName + ".xls", System.Text.Encoding.GetEncoding("GB2312")); response.AddHeader("Content-Disposition", "attachment; filename=" + file); response.Charset = "GB2312"; response.Write(sw.ToString()); response.End(); }
private void ToExcel(System.Data.DataTable dataTable, string path) { try { System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid(); grid.HeaderStyle.Font.Bold = true; grid.DataSource = dataTable; grid.DataMember = dataTable.TableName; grid.DataBind(); // render the DataGrid control to a file using (StreamWriter sw = new StreamWriter(path)) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { grid.RenderControl(hw); } } } catch (Exception ex) { } }
public override void ExecuteResult(ControllerContext context) { var r = context.HttpContext.Response; r.Clear(); r.ContentType = "application/vnd.ms-excel"; if (!string.IsNullOrEmpty(FileName)) r.AddHeader("content-disposition", "attachment;filename=" + FileName); const string header = @"<html xmlns:x=""urn:schemas-microsoft-com:office:excel""> <head> <meta http-equiv=Content-Type content=""text/html; charset=utf-8""> <style> <!--table br {mso-data-placement:same-cell;} tr {vertical-align:top;} --> </style> </head> <body>"; r.Write(header); r.Charset = ""; var dg = new DataGrid(); dg.EnableViewState = false; dg.DataSource = Data; dg.DataBind(); dg.RenderControl(new HtmlTextWriter(r.Output)); r.Write("</body></HTML>"); }
public static void Convert(System.Data.DataSet ds, System.Web.HttpResponse response, string ExcelName) { try { //first let's clean up the response.object response.Clear(); response.Charset = ""; //set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; //create a string writer //response.AddHeader("Content-Disposition", "attachment;filename=Shilpa.xls"); response.AddHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".xls"); System.IO.StringWriter stringWrite = new System.IO.StringWriter(); //create an htmltextwriter which uses the stringwriter System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); //instantiate a datagrid System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); //set the datagrid datasource to the dataset passed in dg.DataSource = ds.Tables[0]; //bind the datagrid dg.DataBind(); //tell the datagrid to render itself to our htmltextwriter dg.RenderControl(htmlWrite); //all that's left is to output the html response.Write(stringWrite.ToString()); response.End(); } catch (Exception ex) { throw ex; } }
public static void Convert(System.Data.DataSet ds, int TableIndex, System.Web.HttpResponse response, string ExcelName) { //lets make sure a table actually exists at the passed in value //if it is not call the base method if (TableIndex > ds.Tables.Count - 1) { Convert(ds, response, ExcelName); } //we've got a good table so //let's clean up the response.object response.Clear(); response.Charset = ""; response.AddHeader("Content-Disposition", "attachment;filename=Shilpa.xls"); //set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; //create a string writer System.IO.StringWriter stringWrite = new System.IO.StringWriter(); //create an htmltextwriter which uses the stringwriter System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); //instantiate a datagrid System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); //set the datagrid datasource to the dataset passed in dg.DataSource = ds.Tables[TableIndex]; //bind the datagrid dg.DataBind(); //tell the datagrid to render itself to our htmltextwriter dg.RenderControl(htmlWrite); //all that's left is to output the html response.Write(stringWrite.ToString()); response.End(); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=CMSPeople.xls"); Response.Charset = ""; var name = "ExtraExcelResult " + DateTime.Now; var tag = DbUtil.Db.PopulateSpecialTag(qid, DbUtil.TagTypeId_ExtraValues); var roles = CMSRoleProvider.provider.GetRolesForUser(Util.UserName); var xml = XDocument.Parse(DbUtil.Db.Content("StandardExtraValues.xml", "<Fields/>")); var fields = (from ff in xml.Root.Elements("Field") let vroles = ff.Attribute("VisibilityRoles") where vroles != null && (vroles.Value.Split(',').All(rr => !roles.Contains(rr))) select ff.Attribute("name").Value); var nodisplaycols = string.Join("|", fields); var cmd = new SqlCommand("dbo.ExtraValues @p1, @p2, @p3"); cmd.Parameters.AddWithValue("@p1", tag.Id); cmd.Parameters.AddWithValue("@p2", ""); cmd.Parameters.AddWithValue("@p3", nodisplaycols); cmd.Connection = new SqlConnection(Util.ConnectionString); cmd.Connection.Open(); var dg = new DataGrid(); dg.DataSource = cmd.ExecuteReader(); dg.DataBind(); dg.RenderControl(new HtmlTextWriter(Response.Output)); }
/// <summary> /// Initialize the control to page. /// </summary> private void InitControlToPage() { System.Web.UI.Control controlToPage = this.Parent.FindControl(this.ControlToPage); if (controlToPage != null) { switch (controlToPage.ToString()) { case "System.Web.UI.WebControls.DataGrid": System.Web.UI.WebControls.DataGrid dataGrid = (System.Web.UI.WebControls.DataGrid)controlToPage; dataGrid.AllowPaging = true; dataGrid.AllowCustomPaging = false; dataGrid.PagerStyle.Visible = false; dataGrid.PageSize = this.PageSize; dataGrid.CurrentPageIndex = this.CurrentPage - 1; dataGrid.DataBind(); if (this.RecordCount == 0) { this.RecordCount = GetRecordCount(dataGrid.DataSource); } break; } } }
public void DataTable2Excel(System.Data.DataTable dtData) { System.Web.UI.WebControls.DataGrid 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) { // 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = "gb2312"; // 导出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Clear(); curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString()); curContext.Response.End(); } }
public bool ExportExcelByDataTable(DataTable dt) { try { System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid(); grid.HeaderStyle.Font.Bold = true; grid.DataSource = dt; grid.DataMember = dt.TableName; grid.DataBind(); //string ExcelName = Application.StartupPath + @"\export\" + string.Format("{0:yyyyMMddhhmmss}", DateTime.Now) + ".xls"; string ExcelName = ""; // render the DataGrid control to a file using (StreamWriter sw = new StreamWriter(ExcelName)) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { grid.RenderControl(hw); } } grid.Dispose(); return(true); } catch { return(false); } }
/// <summary> /// DataTable直接输出Excel /// </summary> /// <param name="dtData">DataTable数据表对象</param> /// <param name="FileName">XLS文件名</param> public static void DataTable2Excel(System.Data.DataTable dtData, string FileName) { System.Web.UI.WebControls.DataGrid 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) { // 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); curContext.Response.Charset = ""; // 导出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } }
/// <summary> /// 导出EXCEL(HTML格式的) /// </summary> /// <param name="ds">要导出的DataSet</param> /// <param name="fileName"></param> public static void CreateEXCEL(DataSet ds, string fileName) { System.Web.UI.WebControls.DataGrid dg = new DataGrid(); dg.DataSource = ds; dg.DataBind(); for (int i = 0; i < dg.Items.Count; i++) { for (int j = 0; j < dg.Items[i].Cells.Count; j++) { dg.Items[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } } System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); System.Web.UI.WebControls.DataGrid DG = dg; DG.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
public void ToExcel(object sender, System.EventArgs e) { try { DataTable dtData = GetDTList(); System.Web.UI.WebControls.DataGrid dgExport = null; System.Web.HttpContext curContext = System.Web.HttpContext.Current; System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (dtData != null && dtData.Rows.Count > 0) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = "UTF-8"; curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312 >"); strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); for (int i = 0; i < dgExport.Items.Count; i++) { for (int j = 0; j < 3; j++) { dgExport.Items[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } } dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); WriteAlertInfo(AlertSuccess); } else { WriteAlertInfo(AlertNoData); } } catch (FisException fe) { this.GridViewExt1.DataSource = GetTable(); this.GridViewExt1.DataBind(); writeToAlertMessage(fe.mErrmsg); } catch (Exception ex) { this.GridViewExt1.DataSource = GetTable(); this.GridViewExt1.DataBind(); writeToAlertMessage(ex.Message); } finally { endWaitingCoverDiv(); } }
/// <summary> /// 将DataTable中的数据导出到指定的Excel文件中 /// </summary> /// <param name="page">Web页面对象</param> /// <param name="tab">包含被导出数据的DataTable对象</param> /// <param name="fileName">Excel文件的名称</param> public static bool Export(System.Web.UI.Page page, System.Data.DataTable tab, string fileName) { bool returnvalue = false; System.Web.HttpResponse httpResponse = page.Response; System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid(); dataGrid.DataSource = tab.DefaultView; dataGrid.AllowPaging = false; dataGrid.HeaderStyle.BackColor = System.Drawing.Color.BurlyWood; dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; dataGrid.HeaderStyle.Font.Bold = true; dataGrid.DataBind(); httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //filename="*.xls"; httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); httpResponse.ContentType = "application/ms-excel"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); dataGrid.RenderControl(hw); string filePath = System.Web.HttpContext.Current.Server.MapPath("/BasicInfo/temp/") + fileName; System.IO.StreamWriter sw = System.IO.File.CreateText(filePath); sw.Write(tw.ToString()); sw.Close(); sw.Dispose(); returnvalue = DownFile(httpResponse, fileName, filePath); httpResponse.End(); return(returnvalue); }
protected void BtnExcelExport_Click(object sender, EventArgs e) { try { string DT = DateTime.Now.ToString("ddMMMyyyyhhmmss"); SqlProcsNew sqlobj = new SqlProcsNew(); DataSet dsCategory = sqlobj.ExecuteSP("Proc_InvoiceLkUp", new SqlParameter() { ParameterName = "@IMode", SqlDbType = SqlDbType.Int, Value = 3 }); if (dsCategory.Tables[0].Rows.Count > 0) { System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = dsCategory.Tables[0]; dg.DataBind(); // THE EXCEL FILE. string sFileName = "InvoiceLkup_" + DT + ".xls"; //sFileName = sFileName.Replace("/", ""); // SEND OUTPUT TO THE CLIENT MACHINE USING "RESPONSE OBJECT". Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=" + sFileName); Response.ContentType = "application/vnd.ms-excel"; EnableViewState = false; System.IO.StringWriter objSW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW); dg.HeaderStyle.Font.Bold = true; dg.HeaderStyle.BackColor = Color.GreenYellow; // SET EXCEL HEADERS AS BOLD. dg.RenderControl(objHTW); Response.Write("<table><tr><td>Invoice Lookup</td></tr></table>"); //+ "</td><td>" + lbltotoutstanding.Text + " " + lbltotdebitcredit.Text + "</td></tr></table>"); // STYLE THE SHEET AND WRITE DATA TO IT. Response.Write("<style> TABLE { border:Solid 1px #999; } " + "TD { border:Solid 1px #D5D5D5; text-align:center } </style>"); Response.Write(objSW.ToString()); Response.End(); dg = null; } else { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alert", "alert('No Data To Export');", true); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alert", "alert('" + ex.Message.ToString() + "');", true); } }
/// <summary> /// 导出Excel文件,转换为可读模式 /// </summary> public static void DataTable2Excel(System.Data.DataTable dtData) { DataGrid dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); try { dgExport.RenderControl(htmlWriter); } catch (Exception e) { Log4Net.LogWrite("err", e.Message); } curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } }
public static void SpanRow(DataGrid dg, int groupColumn, int compareColumn) { int i = 0; int j = 0; int rowSpan; string strTemp = ""; for (i = 0; i < dg.Items.Count; i++) { rowSpan = 1; strTemp = dg.Items[i].Cells[compareColumn].Text; for (j = i + 1; j < dg.Items.Count; j++) { if (string.Compare(strTemp, dg.Items[j].Cells[compareColumn].Text) == 0) { rowSpan += 1; dg.Items[i].Cells[groupColumn].RowSpan = rowSpan; dg.Items[j].Cells[groupColumn].Visible = false; } else { break; } } i = j - 1; } }
public static void toExcel(DataTable td) { System.Web.UI.WebControls.DataGrid dgrid = null; System.Web.HttpContext context = System.Web.HttpContext.Current; System.IO.StringWriter strOur = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (td == null) { return; } context.Response.Write(htmlWriter); context.Response.ContentType = "application/vnd.ms-excel"; context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.Charset = ""; context.Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); strOur = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strOur); dgrid = new DataGrid(); dgrid.DataSource = td.DefaultView; dgrid.AllowPaging = false; dgrid.DataBind(); dgrid.RenderControl(htmlWriter); context.Response.Write("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><style>td{vnd.ms-excel.numberformat:@}</style></head>"); context.Response.Write(strOur.ToString()); context.Response.End(); }
protected override void LoadComponent() { this.InitPage(); System.Web.UI.WebControls.DataGrid baseControl = (System.Web.UI.WebControls.DataGrid)base.GetBaseControl(); this.showHeaderCheck.Checked = baseControl.ShowHeader; this.showFooterCheck.Checked = baseControl.ShowFooter; this.allowSortingCheck.Checked = baseControl.AllowSorting; }
public static void Bind(DataTable dt, DataGrid dg) { if (dt != null) { dg.DataSource = dt; dg.DataBind(); } }
/// <summary> /// Bind datagrid with sorting dataview. /// </summary> /// <param name="dv">DataView</param> /// <param name="dataGrid">DataGrid</param> /// <param name="sortField">Sorting Field</param> /// <param name="keyField">DataGrid's Key Field</param> public static void BindAndSort(DataView dv,DataGrid dataGrid,string sortField,string keyField) { if(dv != null) dv.Sort = sortField; dataGrid.DataSource = dv; dataGrid.DataKeyField=keyField; dataGrid.DataBind(); }
private ASPNetDatagridDecorator(DataGrid DatagridToDecorate, ArrayList HeaderCells) { // // TODO: Add constructor logic here // this.DatagridToDecorate = DatagridToDecorate; AddMergeHeader(HeaderCells); }
/// <summary> /// Bind datagrid with sorting dataview. /// </summary> /// <param name="ds">DataSet</param> /// <param name="dataGrid">DataGrid</param> /// <param name="sortField">Sorting Field</param> /// <param name="keyField">DataGrid's Key Field</param> public static void BindAndSort(DataSet ds,DataGrid dataGrid,string sortField,string keyField) { DataView dataView = ds.Tables[0].DefaultView; dataView.Sort = sortField; dataGrid.DataSource = dataView; dataGrid.DataKeyField=keyField; dataGrid.DataBind(); }
public void DataGridWebControlSupport() { var command = new NpgsqlCommand("select * from data;", Conn); var dr = command.ExecuteReader(); //Console.WriteLine(dr.FieldCount); var dg = new DataGrid(); dg.DataSource = dr; dg.DataBind(); }
public static void Format(System.Web.UI.WebControls.DataGrid obj) { obj.CssClass = "mGrid"; obj.PagerStyle.CssClass = "pgr"; obj.AlternatingItemStyle.CssClass = "alt"; obj.AutoGenerateColumns = false; obj.BorderWidth = 1; obj.BorderColor = System.Drawing.Color.Black; }
private static System.IO.StringWriter GetHtmlTagsfromDatagrid(DataTable datatable) { System.IO.StringWriter stringWriter = new System.IO.StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter); DataGrid dg = new DataGrid(); dg.DataSource = datatable; dg.DataBind(); dg.RenderControl(htmlWrite); return stringWriter; }
private void GenerateCols(DataTable dt,DataGrid dg) { foreach(DataColumn dc in dt.Columns) { BoundColumn bc = new BoundColumn(); bc.HeaderText=dc.ColumnName; bc.DataField=dc.ColumnName; dg.Columns.Add(bc); } }
public void GetControl(System.Web.UI.WebControls.DataGrid _MyGrid, Hashtable _HS, int pagina) { foreach (DataGridItem o_Litem in _MyGrid.Items) { for (int i = 0; i < o_Litem.Cells.Count; i++) { GetVal(o_Litem.Cells[i].Controls, _HS, pagina); } } }
/// <summary> /// The Page_Load event handler on this User Control is used to /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { ViewState["SortField"] = string.Empty; ViewState["SortOrder"] = string.Empty; if (IsEditable) { cmdManage.Visible = true; } else { cmdManage.Visible = false; } } if (Settings["XSLsrc"].ToString().Length > 0 || bool.Parse(Settings["DisplayAsXML"].ToString()) == true) { xmlControl = new UserDefinedTableXML(XmlDataView(), TabID, ModuleIDsrc(), IsEditable, GetSortField(), GetSortOrder()); xmlControl.SortCommand += new UDTXSLSortEventHandler(xmlData_Sort); if (bool.Parse(Settings["DisplayAsXML"].ToString()) == true) { //Show Raw XML xmlText = new TextEditor(); xmlText.Text = xmlControl.InnerXml; xmlText.Width = 450; xmlText.Height = 400; PlaceHolderOutput.Controls.Add((Control)xmlText); } else { //Show XSL data PlaceHolderOutput.Controls.Add(xmlControl); BindXSL(); } } else { //Show datagrid grdData = new DataGrid(); grdData.BorderWidth = 0; grdData.CellPadding = 4; grdData.AutoGenerateColumns = false; grdData.HeaderStyle.CssClass = "NormalBold"; grdData.ItemStyle.CssClass = "Normal"; grdData.AllowSorting = true; grdData.SortCommand += new DataGridSortCommandEventHandler(grdData_Sort); PlaceHolderOutput.Controls.Add(grdData); BindGrid(); } //Rob Siera - 04 nov 2004 - Show ManageButton only when having Permission to edit Properties cmdManage.Visible = ArePropertiesEditable; }
public void DataGridBind(System.Web.UI.WebControls.DataGrid grid) { binded = true; grid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(gridHandler.Sort); gridHandler.Bound(grid, 0, 50); if (!IsPostBack) { grid.DataSource = new DataTable(); grid.DataBind(); } }
protected void BtnnExcelExport_Click(object sender, EventArgs e) { DataSet dsStatement = sqlobj.ExecuteSP("Proc_Events", new SqlParameter() { ParameterName = "@i", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Int, Value = 12 }); if (dsStatement.Tables[0].Rows.Count > 0) { System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = dsStatement.Tables[0]; dg.DataBind(); DateTime dt = DateTime.Now; // THE EXCEL FILE. string sFileName = "Events_" + dt + ".xls"; //sFileName = sFileName.Replace("/", ""); // SEND OUTPUT TO THE CLIENT MACHINE USING "RESPONSE OBJECT". Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=" + sFileName); Response.ContentType = "application/vnd.ms-excel"; EnableViewState = false; System.IO.StringWriter objSW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW); dg.HeaderStyle.Font.Bold = true; dg.HeaderStyle.BackColor = Color.GreenYellow; // SET EXCEL HEADERS AS BOLD. dg.RenderControl(objHTW); Response.Write("<table><tr><td>Upcoming Events List</td></tr></table>"); //+ "</td><td>" + lbltotoutstanding.Text + " " + lbltotdebitcredit.Text + "</td></tr></table>"); // STYLE THE SHEET AND WRITE DATA TO IT. Response.Write("<style> TABLE { border:Solid 1px #999; } " + "TD { border:Solid 1px #D5D5D5; text-align:center } </style>"); Response.Write(objSW.ToString()); Response.End(); dg = null; } else { WebMsgBox.Show("No Events."); } }
public static void Style(DataGrid grid) { grid.CssClass = string.IsNullOrEmpty(grid.CssClass ) ? "Grid" : grid.CssClass; grid.ItemStyle.CssClass = string.IsNullOrEmpty(grid.ItemStyle.CssClass ) ? "GridItem" : grid.ItemStyle.CssClass; grid.EditItemStyle.CssClass = string.IsNullOrEmpty(grid.EditItemStyle.CssClass ) ? "GridEditItem" : grid.EditItemStyle.CssClass; grid.AlternatingItemStyle.CssClass = string.IsNullOrEmpty(grid.AlternatingItemStyle.CssClass ) ? "GridAlternatingItem" : grid.AlternatingItemStyle.CssClass; grid.SelectedItemStyle.CssClass = string.IsNullOrEmpty(grid.SelectedItemStyle.CssClass ) ? "GridSelectedItem" : grid.SelectedItemStyle.CssClass; grid.PagerStyle.CssClass = string.IsNullOrEmpty(grid.PagerStyle.CssClass ) ? "GridPager" : grid.PagerStyle.CssClass; grid.HeaderStyle.CssClass = string.IsNullOrEmpty(grid.HeaderStyle.CssClass ) ? "GridHeader" : grid.HeaderStyle.CssClass; grid.FooterStyle.CssClass = string.IsNullOrEmpty(grid.FooterStyle.CssClass) ? "GridFooter" : grid.FooterStyle.CssClass; }
private void Page_Load(object sender, System.EventArgs e) { HtmlForm frm = (HtmlForm)FindControl("form1"); this.GHTTestBegin(frm); DataGrid grid1 = new DataGrid(); this.GHTBuildSampleDataGrid(grid1); this.TestControls(grid1); DataList list1 = new DataList(); this.GHTBuildSampleDataList(list1); this.TestControls(list1); this.GHTTestEnd(); }
/// <summary> /// Agrega una nueva columna al DataGrid /// </summary> /// <param name="MyDataGrid">Objeto DataGrid a actualizar</param> /// <param name="myDatatable">Objeto Datatable con los datos</param> /// <param name="objBound_column">Objeto BoundColumn a agregar</param> /// <remarks> /// <list> Creado: Diciembre 10 de 2013 - Ing. David Alejandro Pineda Diaz </list> /// </remarks> public static void addBoundColumnToGrid(ref DataGrid MyDataGrid, DataTable myDatatable, BoundColumn objBound_column) { try { MyDataGrid.Columns.Add(objBound_column); updateGrid(ref MyDataGrid, myDatatable); } catch (Exception ex) { throw ex; } }
public void ExportarExcel(DataGrid grid) { this.Response.Clear(); this.Response.AddHeader("content-disposition", "attachment;filename=Arquivo.xls"); this.Response.Charset = ""; this.Response.Cache.SetCacheability(HttpCacheability.NoCache); this.Response.ContentType = "application/vnd.xls"; StringWriter sWr = new StringWriter(); HtmlTextWriter hWr = new HtmlTextWriter(sWr); grid.RenderControl(hWr); this.Response.Write(sWr.ToString()); this.Response.End(); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=CMSOrganizations.xls"); Response.Charset = ""; var d = m.OrganizationExcelList(); var dg = new DataGrid(); dg.DataSource = d; dg.DataBind(); dg.RenderControl(new HtmlTextWriter(Response.Output)); }
public static void fillDataGrid(System.Web.UI.WebControls.DataGrid dg, string config, string sql) { string ConnStr = ConfigurationManager.AppSettings[config]; SqlConnection cn = new SqlConnection(ConnStr); SqlDataAdapter da = new SqlDataAdapter(sql, cn); DataSet ds = new DataSet(); da.Fill(ds, "datasetresult"); dg.DataSource = ds.Tables["datasetresult"].DefaultView; dg.DataBind(); }
public static DataGrid CreateDataGrid() { var dgResults = new DataGrid { PageSize = 30, BorderWidth = 1, BorderStyle = BorderStyle.Solid, BorderColor = System.Drawing.Color.FromArgb(224, 224, 224) }; dgResults.AlternatingItemStyle.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); dgResults.HeaderStyle.Font.Bold = true; return dgResults; }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=CMSStatusFlags.xls"); Response.Charset = ""; var collist = from ss in DbUtil.Db.ViewStatusFlagNamesRoles.ToList() where ss.Role == null || HttpContext.Current.User.IsInRole(ss.Role) select ss; IEnumerable<string> cq = null; if (flags.HasValue()) cq = from f in flags.Split(',') join c in collist on f equals c.Flag select "\tss.{0} as [{0}_{1}]".Fmt(c.Flag, c.Name); else cq = from c in collist where c.Role == null || HttpContext.Current.User.IsInRole(c.Role) select "\tss.{0} as [{1}]".Fmt(c.Flag, c.Name); var tag = DbUtil.Db.PopulateSpecialTag(qid, DbUtil.TagTypeId_StatusFlags); var cols = string.Join(",\n", cq); var cn = new SqlConnection(Util.ConnectionString); cn.Open(); var cmd = new SqlCommand(@" SELECT md.PeopleId, md.[First], md.[Last], md.Age, md.Marital, md.Decision, md.DecisionDt, md.JoinDt, md.Baptism, " + cols + @" FROM StatusFlagColumns ss JOIN MemberData md ON md.PeopleId = ss.PeopleId JOIN dbo.TagPerson tp ON tp.PeopleId = md.PeopleId WHERE tp.Id = @p1", cn); cmd.Parameters.AddWithValue("@p1", tag.Id); var rd = cmd.ExecuteReader(); var dg = new DataGrid(); dg.DataSource = rd; dg.DataBind(); dg.RenderControl(new HtmlTextWriter(Response.Output)); }
//匹配 private void MatchDataGrid(DataGrid dgO) { string strLastSelectedRecord = string.Empty; // System.Collections.Specialized.StringDictionary coll = GlobalFacade.SystemContext.GetContext().GetPageContext(this.Page.ID).LastSelectedRecord; // if(coll != null) // { // string cachedLastSelectedRecord = coll[dgO.UniqueID]; // if(cachedLastSelectedRecord != null && cachedLastSelectedRecord != string.Empty) // strLastSelectedRecord = cachedLastSelectedRecord; // } if (Session[dgO.UniqueID + this.Page.ID] != null && Session[dgO.UniqueID + this.Page.ID].ToString() != string.Empty) { strLastSelectedRecord = Session[dgO.UniqueID + this.Page.ID].ToString(); } if (strLastSelectedRecord == string.Empty) { return; } System.Web.UI.WebControls.DataGrid dg = dgO; for (int j = 0; j < dg.Items.Count; j++) { (dg.Items[j].Cells[0].Controls[1] as CheckBox).Checked = false; } bool flag = false; string tempPKID = string.Empty; for (int j = 0; j < dg.Items.Count; j++) { if (strLastSelectedRecord.IndexOf("'" + dg.Items[j].Cells[1].Text + "'") != -1) { if (dg.Items[j].Cells[1].Text == tempPKID) { continue; } else { (dg.Items[j].Cells[0].Controls[1] as CheckBox).Checked = true; flag = true; tempPKID = dg.Items[j].Cells[1].Text; } } } if (!flag) { if (dg.Items.Count > 0) { (dg.Items[0].Cells[0].Controls[1] as CheckBox).Checked = true; } } }
/// <summary> /// �����ͱ��忡�� Ư�� Row�� Ŭ�������� ���� ��ġ�ϸ� �� Row�� ���� ó��. ������ Row�� ���� /// </summary> /// <param name="dg"></param> /// <param name="li_target_index"></param> /// <param name="ls_compare_value"></param> /// <param name="li_last_index"></param> public void ChangeGridRowStyleBold(DataGrid dg, int li_target_index, string ls_compare_value, int li_last_index) { for (int i = 0;i < dg.Items.Count + (li_last_index);i++) { if (dg.Items[i].Cells[li_target_index].Text == ls_compare_value) { dg.Items[i].Font.Bold = true; } else { dg.Items[i].Font.Bold = false; } } }
public static void ExportDataGrid(string FileType, string FileName, System.Web.UI.WebControls.DataGrid DG) { System.Web.HttpContext.Current.Response.Charset = "GB2312"; System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString()); System.Web.HttpContext.Current.Response.ContentType = FileType; System.Web.UI.Page page = new System.Web.UI.Page(); page.EnableViewState = false; System.IO.StringWriter stringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(stringWriter); DG.RenderControl(writer); System.Web.HttpContext.Current.Response.Write(stringWriter.ToString()); System.Web.HttpContext.Current.Response.End(); }