Excel导出小结(1)

      最近做了个数据导出到excel输出的问题,整个过程比较纠结,现做个简单的回顾总结,以后也方便温故。

      常用的方法是先将数据通过gridview或者repeater控件在页面上输出显示后再进行导出,但此方法遇到数据量比较大时在显示的时候就很耗时,而且显示的时候虽然有滚动条,但美观上也好不到哪里去。(此处可能可以考虑使用cache保存数据,然后在显示的时候做成分页的形式从cache中读取少量数据仅供显示,然后再把cache中的数据导出,待实践)

    于是考虑采取别的做法,先尝试使用HTMLTable,部分代码为:

HtmlTable table = new HtmlTable();
        for (int i = 0; i < 20; i++)
        {
            HtmlTableRow row = new HtmlTableRow();
            for (int j = 0; j < 10; j++)
            {
                HtmlTableCell cell = new HtmlTableCell();
                cell.InnerHtml = i.ToString() + "行" + j.ToString() + "列";
                row.Cells.Add(cell);
            }
            table.Rows.Add(row);
        }

        Response.Clear();
        Response.Buffer = true;       

        Response.ContentType = "application"/vnd.ms-excel;charset=utf-8";
        Response.Charset = "utf-8";
        Response.AppendHeader("Content-Disposition ", "online;filename=File1.excel");
        Response.ContentEncoding = System.Text.Encoding.UTF8;

        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);

        table.RenderControl(oHtmlTextWriter);

        Response.Write(oStringWriter.ToString());//#1
        Response.End();
但以上导出的excel没有网格线

public StringBuilder htmlString()
    {
        StringBuilder str = new StringBuilder();
         str.AppendLine("<html xmlns:x='urn:schemas-microsoft-com:office:excel'>");
         str.AppendLine("<head>");
         str.AppendLine( "<!--[if gte mso 9]><xml>");
         str.AppendLine("        <x:ExcelWorkbook>");
         str.AppendLine( "          <x:ExcelWorksheet>");
         str.AppendLine( "             <x:Name>工作表标题</x:Name>");
         str.AppendLine( "             <x:WorksheetOptions>");
         str.AppendLine( "                 <x:Print>");
         str.AppendLine( "                    <x:ValidPrinterInfo />");
         str.AppendLine( "                   </x:Print>");
         str.AppendLine( "            </x:WorksheetOptions>");
         str.AppendLine( "         </x:ExcelWorksheet>");
         str.AppendLine( "       </x:ExcelWorksheets>");
         str.AppendLine( "  </x:ExcelWorkbook>");
         str.AppendLine( " </xml>");
         str.Append( "<![endif]-->");
         str.AppendLine( "</head>");
         str.AppendLine( "<body>");
        return str;
    }

上述#1处改成:

Response.Write(htmlString().ToString() + oStringWriter.ToString() + "</body></html>");

此方法相当于得到了一个table,只是跳过了页面的显示直接输出成excel,而且经过研究可以发现其仍是将table先转成htmlstring后再导出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值