我正在开发一个具有 gridview 控件的网页。我需要将数据传输为 .xls 格式。我能够创建 .xls 文件并传输数据,但问题是我需要将网格单元格显示在 Excel 工作表的背景中。现在,它只显示没有网格单元的空白背景。否则,gridview 会被很好地转移。由于这个问题,打印 .xls 文件是个问题。具有更多列的表格不会压缩,而是打印 2-3 页。我的代码如下:
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();
}
}
}
有什么建议么?