我正在研究一個具有gridview控件的網頁。我需要將數據轉換爲.xls格式。我可以創建.xls文件並傳輸數據,但問題是我需要將網格單元格顯示在Excel表格的背景中。現在,它只顯示沒有網格單元的空白背景。否則,gridview會正常傳輸。由於此問題,打印.xls文件是一個問題。具有更多列的表格不是壓縮,而是打印2-3頁。我的代碼如下:將gridview導出爲.xls
public static void ExportToXLS(string fileName, GridView gv,string companyName,string reportTitle , string period)
{
//For writing to XLS file
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table tableReport = new Table();
tableReport.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
ReportList.PrepareControlForExport(gv.HeaderRow);
tableReport.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ReportList.PrepareControlForExport(row);
tableReport.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
ReportList.PrepareControlForExport(gv.FooterRow);
tableReport.Rows.Add(gv.FooterRow);
}
//Takes value of company name
System.Web.UI.WebControls.Label labelCompany = new System.Web.UI.WebControls.Label();
labelCompany.Text = companyName;
labelCompany.Font.Bold = true;
//Takes value of report title
System.Web.UI.WebControls.Label labelReport = new System.Web.UI.WebControls.Label();
labelReport.Text = reportTitle;
labelReport.Font.Bold = true;
//Takes value of report period
System.Web.UI.WebControls.Label labelPeriod = new System.Web.UI.WebControls.Label();
labelPeriod.Text = period;
// render the htmlwriter into the response
htw.Write("<center>");
labelCompany.RenderControl(htw);
htw.Write("<br/>");
labelReport.RenderControl(htw);
htw.Write("<br/>");
labelPeriod.RenderControl(htw);
htw.Write("</center>");
htw.Write("<br/>");
tableReport.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
有什麼建議嗎?
你想在xls中顯示網格線? – 2012-04-20 06:18:48
請謹慎接受答案..它會讓你很快得到答案。 – 2012-04-20 07:39:14
hello bhavna您是否得到了這項工作,因爲我也面臨同樣的問題 – rahul 2012-09-28 07:00:25