asp.net导出Excel带合并单元格

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.Excel.WebForm2" %>

实现思路:用HTML设计带有合并单元格的Table,再导出成Excel文档。

前端代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.Excel.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table id="table1" runat="server" cellspacing="0">
            <tr>
                <td rowspan="3"  style="width:174px; text-align:center;">
                   
                    数据1</td>
                <td rowspan="2" style="width:80px;">
                  
                    数据2</td>
                <td style="width:80px;">
                    数据4</td>
            </tr>
            <tr>
                <td>
                    数据5</td>
            </tr>
            <tr>
                <td>
                    数据3</td>
                <td>
                    数据6</td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>


后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication1.Excel
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            string attachment = "attachment; filename=Payroll.xls";
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            table1.Border = 1;
            table1.RenderControl(htw);
            string startHtml = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">";
            string endHtml = "</html>";
            Response.Write(startHtml + sw.NewLine + sw.ToString() + endHtml);
            Response.End(); 
        }
    }
}

 

导出结果图:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值