<%@ 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();
}
}
}
导出结果图: