Jus*_*n C 4 .net asp.net excel gridview export
我有一个GridView,我想导出到Excel.当我使用我在网上找到的示例代码时,它将内容导出到Excel就好了,但由于某种原因,它还清除了导出表外的所有网格线.
对于普通的Excel用户来说,这很容易修复,但我需要这个解决方案适合所有人.
那么有没有办法将GridView中的数据导出到Excel工作簿中,看起来它只是输入到Excel中?我已粘贴下面使用的代码,假设名为toPrint的GridView存在且具有准确的数据.
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + name + "_Registration_Forms.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Page.EnableViewState = false;
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
toPrint.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Run Code Online (Sandbox Code Playgroud)
编辑:找到一个部分解决方案.如果我导出为逗号分隔列表并将标题设置为CSV文件,它将打开正常,并显示所有网格线(甚至是导出数据之外的那些).当然,唯一的问题是在导出之前必须从我的值中删除每个逗号和换行符.
小智 5
以下帖子给了我答案.http://forums.asp.net/t/1074110.aspx 我将总结如何处理代码.
System.IO.StringWriter dvWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter OutputGenerator = new System.Web.UI.HtmlTextWriter(dvWriter);
//To put in the excel gridlines
dvWriter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
dvWriter.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>");
//*******Put your Table Body here *******
Run Code Online (Sandbox Code Playgroud)