2009-09-24 19 views
0

這裏是佈局,我有一個FormView控件,它帶有從SQL服務器進來的動態數據。我正在使用FormView的ReadOnly模式。我如何調整PrepareFormViewForExport方法來移除文本框並將FormView中的值留在後面?現在輸出顯示標籤,但將文本框中的值刪除。FormView to Excel - 如何從模板中的控件中拉取數據以放置在單元格中

這是單擊導出按鈕時的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]); 
     } 
    } 
} 

回答

1

嗯,我找到了一個解決辦法,而不是一個真正的sollution。由於我的表單是在ReadOnly中,我將控件從文本框更改爲標籤。這使得html編寫器將數據轉儲到Excel中,而不是試圖複製文本框。我仍然有興趣知道是否有人知道如何回答原來的問題。

相關問題