FormView到Excel – 如何从模板中的控件拉出数据放置在单元格中

这里是布局,我有一个从SQL服务器进来的dynamic数据的FormView控件。 我正在使用FormView的ReadOnly模式。 我怎样才能调整PrepareFormViewForExport方法来删除文本框,并保留FormView中的值? 现在输出显示标签,但从文本框中删除值。

这是单击导出button时的C#代码。

protected void Bexport_Click(object sender, EventArgs e) { //Clear the Response object Response.Clear(); //set Response header to the Excel filename required (.xls for excel, .doc for word) Response.AddHeader("content-disposition", "attachment;filename=ReportOuput.xls"); Response.Charset = ""; // If you want the option to open the Excel // file without the save option then un-comment out the line below //Response.Cache.SetCacheability(HttpCacheability.NoCache); //FOR EXCEL Response.ContentType = "application/vnd.xls"; //FOR WORD //Response.ContentType = "application/vnd.doc"; //Declare new stringwriter and html writer StringWriter stringWrite = new System.IO.StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); //Strip out controls from FormView ?takes data too? PrepareFormViewForExport(FormView2); //render controls data as HTML FormView2.RenderControl(htmlWrite); //Clean out the Javascript postbacks etc. string html = stringWrite.ToString(); html = Regex.Replace(html, "</?(a|A).*?>", ""); StringReader reader = new StringReader(html); //Write xls document Response.Write(html); //end current Response HttpContext.Current.Response.End(); } 

这是从FormView中删除控件的方法,然后再将其导出。

 private void PrepareFormViewForExport(Control fv) { LinkButton lb = new LinkButton(); Literal l = new Literal(); string name = String.Empty; TextBox TB = new TextBox(); for (int i = 0; i < fv.Controls.Count; i++) { if (fv.Controls[i].GetType() == typeof(LinkButton)) { l.Text = (fv.Controls[i] as LinkButton).Text; fv.Controls.Remove(fv.Controls[i]); fv.Controls.AddAt(i, l); } else if (fv.Controls[i].GetType() == typeof(TextBox)) { l.Text = (fv.Controls[i] as TextBox).Text; fv.Controls.Remove(fv.Controls[i]); fv.Controls.AddAt(i, l); } else if (fv.Controls[i].GetType() == typeof(DropDownList)) { l.Text = (fv.Controls[i] as DropDownList).SelectedItem.Text; fv.Controls.Remove(fv.Controls[i]); fv.Controls.AddAt(i, l); } else if (fv.Controls[i].GetType() == typeof(CheckBox)) { l.Text = (fv.Controls[i] as CheckBox).Checked ? "True" : "False"; fv.Controls.Remove(fv.Controls[i]); fv.Controls.AddAt(i, l); } if (fv.Controls[i].HasControls()) { PrepareFormViewForExport(fv.Controls[i]); } } } 

尝试传播Sheet Gear第三方组件http://www.spreadsheetgear.com/

那么我find了一个解决方法,而不是一个真正的溶剂。 由于我的表单是在ReadOnly我改变了控件从文本框到标签。 这使得html编写器将数据转储到Excel中,而不是试图复制文本框。 我仍然有兴趣知道是否有人知道如何回答原来的问题。