[转]Excel2003和2007可共用的导出方法

最近刚好在写Excel的web程序,翻到了一片更新,转过来慢慢研究,摘自http://www.cnblogs.com/ahui/archive/2009/03/30/1425186.html

/// <summary>
/// 从DataSet导出Excel
/// </summary>
/// <param name="ds"></param>
/// <param name="headTexts"></param>
/// <param name="fields"></param>
/// <param name="styles">样式,如果要显示为字符串,可设置为vnd.ms-excel.numberformat:@</param>
/// <param name="cssNames"></param>
public void ExportDataSetToExcel(DataSet ds, string[] headTexts, string[] fields, string[] formats, string[] styles, string fileName)
{
    // 检测参数
    if (ds == null || ds.Tables.Count == 0)
    {
        Alert("数据源为空!");
        return;
    }
    if (headTexts == null || fields == null || headTexts.Length != fields.Length || headTexts.Length > ds.Tables[0].Columns.Count)
    {
        Alert("参数与数据源不匹配!");
        return;
    }
    if (formats != null)
    {
        if (formats.Length < headTexts.Length)
        {
            string[] tmp = formats;
            formats = new string[headTexts.Length];
            tmp.CopyTo(formats, 0);
            tmp = null;
        }
    }
    if (styles != null)
    {
        if (styles.Length < headTexts.Length)
        {
            string[] tmp = styles;
            styles = new string[headTexts.Length];
            tmp.CopyTo(styles, 0);
            tmp = null;
        }
    }

    if (Common.StringUtils.IsNullOrEmpty(fileName))
    {
        fileName = string.Format("excel{0:yyyyMMdd}.xls", DateTime.Now);
    }

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "UTF-8";
    Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.ContentEncoding = System.Text.Encoding.Default;
    Response.ContentType = "application/ms-excel";
    this.EnableViewState = false;
    Response.Write("<table cellspacing='0' rules='all' border='1' style='border-collapse:collapse;'>");

    // 表头
    Response.Write("<thead>");
    foreach (string headText in headTexts)
    {
        Response.Write(string.Format("<th>{0}</th>", headText));
    }
    Response.Write("</thead>");

    foreach (DataRow row in ds.Tables[0].Rows)
    {
        Response.Write("<tr>");
        for (int i = 0; i < headTexts.Length; ++i)
        {
            Response.Write("<td");
            if (styles != null && Common.StringUtils.IsNullOrEmpty(styles[i]) == false)
            {
                Response.Write(string.Format(" style=\"{0}\"", styles[i]));
            }
            Response.Write(">");
            if (formats != null && Common.StringUtils.IsNullOrEmpty(formats[i]) == false)
            {
                Response.Write(string.Format(formats[i], row[fields[i]]));
            }
            else
            {
                Response.Write(row[fields[i]]);
            }
            Response.Write("</td>");
        }
        Response.Write("</tr>");
    }
    Response.Write("</table>");
    Response.End();
}
posted @ 2009-03-30 16:18  梳子  阅读(943)  评论(0编辑  收藏  举报