zoukankan      html  css  js  c++  java
  • ASP.NET列表信息以Excel形式导出

    1.从数据查出数据扔进table中:
    
    private DataTable getTable()
    {
    var dbHelper = applyBLL.CreateDataBase("VISAdoDb");
    StringBuilder SB = new StringBuilder();
    SB.AppendFormat("Select ApplyForID,Applicants,CardNo from VIS_ApplyFor where iState = 0 and (ApplyState ='B01')");
    DbCommand cmd = dbHelper.GetSqlStringCommand(SB.ToString());
    DataSet DTab = dbHelper.ExecuteDataSet(cmd);
    
    if (DTab != null && DTab.Tables != null && DTab.Tables.Count > 0 && DTab.Tables[0].Rows.Count > 0)
    {
    DataTable dt = DTab.Tables[0];
    return dt;
    }
    else
    {
    return new DataTable();
    }
    }
    2.用xml文件定义要输出的表头元素:
    
    string xml = string.Empty;
    
    xml = "../../../App_Data/Configs_Pages/HDDXReportAuth.xml";
    Dictionary<string, string> dict = Common.XMLHelper.GetDictionaryByXML(xml);
    
    xml文件:
    
    <?xml version="1.0" encoding="utf-8" ?>
    <ExcelDict Remark="核对对象导出名单">
    <Field Name="ApplyForID" Value="主键" Visible="False"></Field>
    <Field Name="Applicants" Value="申请人姓名"></Field>
    <Field Name="CardNo" Value="证件号码"></Field>
    </ExcelDict>
    
    3.最关键的一步,将model对象转换为excel
    
     bool i = ModelToExcel.ExExcel(dt, "核对对象导出名单", dict, false, "", ref result);
    
    /// <summary> 
    /// 将一组对象导出成EXCEL 
    /// </summary> 
    /// <typeparam name="T">要导出对象的类型</typeparam> 
    /// <param name="objList">一组对象</param> 
    /// <param name="FileName">导出后的文件名</param> 
    /// <param name="columnInfo">列名信息</param> 
    /// <param name="IsExTotal">是否导出合计信息</param>
    /// <param name="TotalMess">合计信息字符串</param>
    public static bool ExExcel(DataTable objList, string FileName, Dictionary<string, string> columnInfo, bool IsExTotal, string TotalMess, ref string result)
    {
    FileName = FileName + "_" + DateTime.Now.ToString("yyyyMMddHH");
    if (columnInfo.Count == 0)
    {
    //OutputResult(false, "请联系管理员,系统配置有问题!"); 
    result = "请联系管理员,系统配置有问题!";
    return false;
    }
    if (objList.Rows.Count == 0)
    {
    //OutputResult(false, "没有查询到数据");
    result = "没有查询到数据";
    return false;
    }
    
    string TmepUrl = "Temp/" + DateTime.Now.ToString("yyyyMMddhhmmss") + "/";
    string path = System.Web.HttpContext.Current.Server.MapPath("~/" + TmepUrl);
    if (!Directory.Exists(path)) //如果文件夹不存在则创建
    {
    Directory.CreateDirectory(path);
    }
    if (!File.Exists(path + FileName + ".xls"))
    {
    //使用File.Create创建再复制/移动/删除时会提示:文件正由另一进程使用,因此该进程无法访问该文件
    //改用 FileStream或StreamWriter 获取 File.Create 返回的 System.IO.FileStream 再进行关闭就无此问题
    using (FileStream sw = new FileStream(path + FileName + ".xls", FileMode.Create))
    {
    }
    }
    
    //生成EXCEL的HTML 
    System.Text.StringBuilder excelStr = new System.Text.StringBuilder();
    excelStr.Append("<table cellspacing="0" cellpadding="5" rules="all" border="1">");
    excelStr.Append("<tr style="height:50px; font-weight:bold;font-size:20pt" align="center">");
    excelStr.Append("<td colspan='" + Convert.ToString(columnInfo.Count + 1) + "'>");
    excelStr.Append(FileName);
    excelStr.Append("</td>");
    excelStr.Append("</tr>");
    //是否导出合计信息
    if (IsExTotal)
    {
    excelStr.Append("<tr style="height:30px;" align="right">");
    excelStr.Append("<td colspan='" + Convert.ToString(columnInfo.Count + 1) + "'>");
    excelStr.Append(TotalMess);
    excelStr.Append("</td>");
    excelStr.Append("</tr>");
    }
    
    //Type myType = objList.Columns.GetType();
    //根据反射从传递进来的属性名信息得到要显示的属性 
    List<DataColumn> myPro = new List<DataColumn>();
    excelStr.Append("<tr style="height:30px;">");
    excelStr.Append("<td>序号</td>");
    foreach (string cName in columnInfo.Keys)
    {
    DataColumn p = objList.Columns[cName]; //myType.GetProperty(cName);
    if (p != null)
    {
    myPro.Add(p);
    excelStr.Append("<td>");
    excelStr.Append(columnInfo[cName]);
    excelStr.Append("</td>");
    }
    }
    excelStr.Append("</tr>");
    //如果没有找到可用的属性则结束 
    if (myPro.Count == 0) { result = "请联系管理员,系统配置有问题!"; return false; }
    int index = 0;
    foreach (DataRow obj in objList.Rows)
    {
    excelStr.Append("<tr style="height:30px;">");
    excelStr.Append("<td style="vnd.ms-excel.numberformat:@" >" + (++index).ToString() + "</td>");
    foreach (DataColumn p in myPro)
    {
    excelStr.Append("<td style="vnd.ms-excel.numberformat:@" >");
    object value = obj[p.ColumnName];
    if (p.DataType.Name.ToLower() == "datetime")
    {
    value = (value == null || string.IsNullOrEmpty(value.ToString())) ? "" : ((DateTime)value).ToString("yyyy-MM-dd");
    }
    else if(p.DataType.Name.ToLower()=="decimal"){
    value = (value == null || string.IsNullOrEmpty(value.ToString())) ? "" : string.Format("{0:F2}", value); 
    }
    excelStr.Append(value);
    excelStr.Append("</td>");
    }
    
    excelStr.Append("</tr>");
    }
    excelStr.Append("</table>");
    //输出EXCEL 
    System.Text.StringBuilder ExportStr = new System.Text.StringBuilder();
    ExportStr.Append("<html><head><META http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body>");
    ExportStr.Append(excelStr);
    ExportStr.Append("</body></html>");
    
    string Weburl = System.Web.HttpContext.Current.Request.ApplicationPath + TmepUrl + FileName + ".xls";
    
    using (StreamWriter sw = new StreamWriter(path + FileName + ".xls", false, System.Text.Encoding.GetEncoding("utf-8")))
    {
    sw.Write(ExportStr);
    sw.Close();
    }
    result = Weburl;
    return true;
    }
    #endregion 
    }
    
     
    

      


    海的呐喊
  • 相关阅读:
    .net core读取appsettings.config中文乱码问题
    vs2017错误:当前页面的脚本发生错误
    VS Code中无法识别npm命令
    Visual Studio报错/plugin.vs.js,行:1074,错误:缺少标识符、字符串或数字
    记录一次在生成数据库服务器上出现The timeout period elapsed prior to completion of the operation or the server is not responding.和Exception has been thrown by the target of an invocation的解决办法
    Java集合框架
    java hash表
    Java Dictionary 类存储键值
    java数据结构 栈stack
    java封装
  • 原文地址:https://www.cnblogs.com/kejie/p/5093263.html
Copyright © 2011-2022 走看看