我正在尝试导出excel网格视图数据。我可以绑定excel中的数据。但是当我打开网格视图时,我丢失了看起来非常糟糕的网格线。我在下面添加了我的代码。
此代码获取我的网格数据并将其导出为excel删除所有网格线我试图谷歌找不到一个突破可以有人帮我这个
protected void btn_export_Click(object sender, EventArgs e)
{
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "Dashboard_FOR_PM" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
grv_dashboard.GridLines = GridLines.Both;
grv_dashboard.HeaderStyle.Font.Bold = true;
grv_dashboard.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table table = new Table();
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth=new Unit(1);
table.BorderColor = System.Drawing.Color.Black;
table.GridLines = GridLines.Both;
}
}
strwritter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
strwritter.Write(@"<head>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:WorksheetOptions>
<x:Panes></x:Panes>
<x:Print><x:Gridlines /></x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>");
Response.End();
}
答案 0 :(得分:0)
看看我之前写过的下面的功能,请询问是否有不清楚的地方,希望有所帮助
public void ToExcel(DataTable dt, string reportName)
{
if (dt.Rows.Count > 0)
{
string filename = string.Format("{0}.xls", reportName);
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
HtmlForm hf = new HtmlForm();
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.HeaderStyle.BackColor = Color.Tomato;//change to your own colors
dg.HeaderStyle.ForeColor = Color.White;//change to your own colors
dg.BackColor = Color.LightGoldenrodYellow;//change to your own colors
dg.AlternatingItemStyle.BackColor = Color.PaleGoldenrod;//change to your own colors
dg.Font.Name = "Tahoma";
dg.Font.Size = 10;
dg.GridLines = GridLines.Both;
dg.BorderColor = System.Drawing.Color.Black;
dg.BorderStyle = BorderStyle.Solid;
dg.BorderWidth = new Unit(1);
dg.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Current.Response.Charset = "";
EnableViewState = false;
Controls.Add(hf);
hf.Controls.Add(dg);
hf.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}