本文原创地址:http://blog.csdn.net/ranbolwb/article/details/8083983 ,转载请保留本行。
本例子是上一篇 DataTable 导出 Excel 的进阶,除了上一篇提到的处理乱码问题,本例还添加了处理多行表头、合并单元格的功能及处理中文文件名乱码问题,应该可以满足日常开发的需要了。
废话不多说了,直接上代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
/// <summary>
/// Common 的摘要说明
/// 作者:李伟波
/// 时间:2012-10-18
/// </summary>
public class Common
{
public Common()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 描述:把DataTable内容导出excel并返回客户端
/// 作者:李伟波
/// 时间:2012-10-18
/// </summary>
/// <param name="dtData"></param>
/// <param name="header"></param>
/// <param name="fileName"></param>
/// <param name="mergeCellNums">要合并的列索引字典 格式:列索引-合并模式(合并模式 1 合并相同项、2 合并空项、3 合并相同项及空项)</param>
/// <param name="mergeKey">作为合并项的标记列索引</param>
public static void DataTable2Excel(System.Data.DataTable dtData, TableCell[] header, string fileName, Dictionary<int, int> mergeCellNums, int? mergeKey)
{
System.Web.UI.WebControls.GridView gvExport = null;
// 当前对话
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
// IO用于导出并返回excel文件
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";