asp.net中通过html格式导出excel文件

时间:2021-08-10 05:40:29
//通过html格式生成导出excel文件,下载保存。  
StreamExport(wgMdcStaff5, fileName, ToDataTable<MdcDrugProcureStockViewDto>(response.responseObjects));
   调用方法// 
//把实体集合对象转化成datatable类型的数据
public static System.Data.DataTable ToDataTable<T>(List<T> entitys)
    {
        //检查实体集合不能为空
        if (entitys == null || entitys.Count < 1)
        {
            throw new Exception("需转换的集合为空");
        }
        //取出第一个实体的所有Propertie
        Type entityType = entitys[0].GetType();
        PropertyInfo[] entityProperties = entityType.GetProperties();
        //生成DataTable的structure
        //生产代码中,应将生成的DataTable结构Cache起来,此处略
        System.Data.DataTable dt = new System.Data.DataTable();
        for (int i = 0; i < entityProperties.Length; i++)
        {
            Type colType = entityProperties[i].PropertyType;
            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                colType = colType.GetGenericArguments()[0];
            }
            dt.Columns.Add(entityProperties[i].Name, colType);
        }
        //将所有entity添加到DataTable中
        foreach (object entity in entitys)
        {
            //检查所有的的实体都为同一类型
            if (entity.GetType() != entityType)
            {
                throw new Exception("要转换的集合元素类型不一致");
            }
            object[] entityValues = new object[entityProperties.Length];
            for (int i = 0; i < entityProperties.Length; i++)
            {
                entityValues[i] = entityProperties[i].GetValue(entity, null) == null ? DBNull.Value : entityProperties[i].GetValue(entity, null);
            }
            dt.Rows.Add(entityValues);
        }
        return dt;
    }

    /// <summary>  
    /// 通过流导出Excel  
    /// </summary>  
    /// <param name="ds">数据源DataSet</param>  
    /// <param name="fileName">保存文件名(例如:a.xls)</param>  
    /// <returns></returns>  
    public bool StreamExport(WsdGrid wsdGrid, string fileName, System.Data.DataTable dt)
    {
        if (fileName == string.Empty)
        {
            return false;
        }
        StringBuilder content = new StringBuilder();
        int i = 0;
        int cl = wsdGrid.Columns.Count;
        content.Append("<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'>");
        content.Append("<head><title></title><meta http-equiv='Content-Type' content=\"text/html; charset=gb2312\">");
        //注意:[if gte mso 9]到[endif]之间的代码,用于显示Excel的网格线,若不想显示Excel的网格线,可以去掉此代码
        content.Append("<!--[if gte mso 9]>");
        content.Append("<xml>");
        content.Append(" <x:ExcelWorkbook>");
        content.Append("  <x:ExcelWorksheets>");
        content.Append("   <x:ExcelWorksheet>");
        content.Append("    <x:Name>" + fileName + "</x:Name>");
        content.Append("    <x:WorksheetOptions>");
        content.Append("      <x:Print>");
        content.Append("       <x:ValidPrinterInfo />");
        content.Append("      </x:Print>");
        content.Append("    </x:WorksheetOptions>");
        content.Append("   </x:ExcelWorksheet>");
        content.Append("  </x:ExcelWorksheets>");
        content.Append("</x:ExcelWorkbook>");
        content.Append("</xml>");
        content.Append("<![endif]-->");
        content.Append("</head><body><table> ");
        //标题
        //content.Append("<tr align='center'><td colspan='" + wsdGrid.Columns.Count + "'><strong>" + fileName + "</strong></td></tr>");
        //content.Append("<tr align='center'></tr>");
        content.Append("<tr align='center'> <td colspan='" + wsdGrid.Columns.Count + "'>");
        content.Append("<table border='1' >");
        content.Append("<tr align='center' >");
        for (i = 0; i < cl; i++)
        {
            content.Append("<td>" + wsdGrid.Columns[i].HeaderText.ToString() + "</td>");
        }
        content.Append("</tr>");
        //逐行处理数据  
        foreach (DataRow row in dt.Rows)
        {
            for (i = 0; i < cl; i++)
            {
                //头加tr
                if (i == 0)
                    content.Append("<tr align='center' >");
                object obj = row[wsdGrid.Columns[i].UniqueName];
                Type type = obj.GetType();
              
                    if (type.Name == "Int32" || type.Name == "Single" || type.Name == "Double" || type.Name == "Decimal" || type.Name == "DateTime")
                    {
                        if (type.Name == "DateTime")
                            content.AppendFormat("<td style='vnd.ms-excel.numberformat:yyyy-mm-dd'>{0}</td>", obj);
                        else if (type.Name == "Int32")
                            content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0'>{0}</td>", obj);
                        else
                        {
                             //设置如果为数字型的保留两位小数
                             if (wsdGrid.Columns[i].UniqueName == "storageQty"|| wsdGrid.Columns[i].UniqueName =="storageSumQty")
                            {
                                content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0'>{0}</td>", obj);
                            }
                            else
                             content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0.00'>{0}</td>", obj);
                        }
                    }
                    else
                        content.AppendFormat("<td style='vnd.ms-excel.numberformat:@'>{0}</td>", obj);
                //尾加/tr
                if (i == cl - 1)
                    content.Append("</tr>");
            }
        }
        content.Append("</table></td></tr>");
        content.Append("</table></body></html>");
        content.Replace("&nbsp;", "");
        System.Web.HttpContext.Current.Response.Clear();
        System.Web.HttpContext.Current.Response.Buffer = true;
        System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
        //System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        System.Web.HttpContext.Current.Response.Charset = "GB2312";
        System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
        System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
        System.Web.HttpContext.Current.Response.Write(content.ToString());
        System.Web.HttpContext.Current.Response.End();
        return true;
    }  

本文出自 “zhangjingjing” 博客,请务必保留此出处http://zhjjzhjj.blog.51cto.com/1802676/984429