当前位置:编程学习 > C#/ASP.NET >>

.net c#如何导出excel在每一列加上标题


public partial class DataToExcel : System.Web.UI.Page 

protected void Page_Load(object sender, EventArgs e) 

DataAccess.DataClassesDataContext db = new DataClassesDataContext(); 
var qu = from t in db.TXLInfos 
select t; 
Response.AppendHeader("Content-Disposition", "attachment;filename=result.xls"); 
Response.ContentType = "application/ms-excel"; 
Response.Charset = "gb2312"; 
Response.ContentEncoding = Encoding.GetEncoding("gb2312"); 
System.IO.StringWriter writer = new System.IO.StringWriter(); 
foreach(TXLInfo item in qu) 

writer.Write(item.GQName); 
writer.Write("t"); 
writer.Write(item.GQID); 
writer.WriteLine(); 

Response.Write(writer.ToString()); 
Response.End(); 





这是网上找的方法,现在只能导出每列的数据,我想要在每列数据加上标题该如何实现呢?

现有数据导出的结果是:
张三  1
李四  2
王五  3

我想要的是:
姓名  id
张三  1
李四  2
王五  3
excel c# .net --------------------编程问答-------------------- 要么你在页面中就加好标题,一起导出,要么就导出后自己处理一下吧 --------------------编程问答-------------------- 自己百度怎么给导出数据加标题,到处excel现在网上实例多如牛毛,俺们是代码搬运工,也是要百度的。 --------------------编程问答-------------------- 要么用 npoi  要么就去创建一张表 然后  给表字段  设定名字   在把数据插入到表里面去 在导出表 --------------------编程问答--------------------
引用 1 楼 bdmh 的回复:
要么你在页面中就加好标题,一起导出,要么就导出后自己处理一下吧



我就是想"加好标题,一起导出",关键是怎么实现啊,我发帖就是问这个问题来的.


  writer.Write(item.GQName);
  writer.Write("t");  
  writer.Write(item.GQID);
  writer.WriteLine(); 

上面这段代码就是只能导出姓名和id的数据  --------------------编程问答-------------------- 在你循环的集合当中先增加一行标题 --------------------编程问答--------------------
引用 5 楼 zifengshen1981 的回复:
在你循环的集合当中先增加一行标题

....我要会我就不问了 --------------------编程问答--------------------
引用 3 楼 cxmaran 的回复:
要么用 npoi  要么就去创建一张表 然后  给表字段  设定名字   在把数据插入到表里面去 在导出表

npoi弄不懂啊.建表插入数据再查数据再导出也太麻烦了吧.... --------------------编程问答-------------------- 就不能在我给出的代码的基础上加上点什么吗??? --------------------编程问答--------------------
#region 将Datatable导出至CSV 重载+1
        /// <summary>
        /// 的形式生成导出
        /// </summary>
        /// <param name="table">要导出的表</param>
        /// <param name="fieldsDescr"><ColumnName,Descipt[,#String|#Datetime]> 以此格式的字段说明</param>
        /// <param name="IsOutNoFields">是不输出filedsDescr不包含的列</param>
        /// <returns>生成的HTML</returns>
        public static String ExportCSV(DataTable table, List<String> fieldsDescr, Boolean IsOutNoFields)
        {
            StringBuilder strCSV = new StringBuilder();

            //先导标题行
            for (int i = 0; i < table.Columns.Count; i++)
            {
                DataColumn cl = table.Columns[i];

                var query = from c in fieldsDescr
                            where c.IndexOf(cl.ColumnName + ",") != -1
                            select c;
                //有说明否
                if (query.Count() < 1 && !IsOutNoFields)
                    continue;

                if (query.Count() < 1)
                    strCSV.Append(cl.ColumnName);
                else
                {
                    String c = query.First();
                    Regex reg = new Regex(@",\w*,?");
                    Match m = reg.Match(c);

                    if (m.Success)
                        strCSV.Append(m.Value.Replace(",", ""));
                    else
                        strCSV.Append(cl.ColumnName);
                }

                if (i + 1 < table.Columns.Count)
                    strCSV.Append(",");
            }

            strCSV.Append("\r\n");

            //生成数据
            foreach (DataRow r in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    var query = from c in fieldsDescr
                                where c.IndexOf(table.Columns[i].ColumnName + ",") != -1
                                select c;

                    //有说明否
                    if (query.Count() < 1 && !IsOutNoFields)
                        continue;


                    if (query.Count() < 1)
                        strCSV.Append(r[i].ToString());
                    else
                    {
                        String cl = query.First();
                        if (cl.IndexOf(",#String") != -1 || cl.IndexOf(",#Datetime") != -1)
                            strCSV.Append("#" + r[i].ToString());
                        else
                            strCSV.Append(r[i].ToString());
                    }

                    if (i + 1 < table.Columns.Count)
                        strCSV.Append(",");
                }
                strCSV.Append("\r\n");
            }

            return strCSV.ToString();
        }
        #endregion
 String strCSV = ExportCSV(tab, new List<String>() { 
                 "Id,标识",
                 "Name,姓名"
            }, false);

                    String strFile = HttpUtility.HtmlEncode("Employee.csv");
                    return File(Encoding.GetEncoding("GB2312").GetBytes(strCSV), "application/octet-stream", strFile);
--------------------编程问答-------------------- 这句话不对啊return  File(Encoding.GetEncoding("GB2312").GetBytes(strCSV), "application/octet-stream", strFile);

File是方法还是类型啊? --------------------编程问答-------------------- try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "UTF-8";
                string filename = this.Title + System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + ".xls";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename));
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                //  Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 

                dto_Complaint_Info.Sign = 0;
                dto_Complaint_Info.StartDate = txtCreateDateBegin.Value;
                dto_Complaint_Info.ResetUser = txtCreateDateEnd.Value == "" ? "" : Convert.ToDateTime(txtCreateDateEnd.Value).AddDays(1).ToString("yyyy-MM-dd");
                if (txtCreateDateBegin.Value == "" && txtCreateDateEnd.Value != "")
                {
                    dto_Complaint_Info.ResetUser = txtCreateDateEnd.Value;
                }

                dto_Complaint_Info.ShenPiDate = txtShenPiDateBegin.Value;
                dto_Complaint_Info.ShenPiUser = txtShenPiDateEnd.Value == "" ? "" : Convert.ToDateTime(txtShenPiDateEnd.Value).AddDays(1).ToString("yyyy-MM-dd");
                if (txtShenPiDateBegin.Value == "" && txtShenPiDateEnd.Value != "")
                {
                    dto_Complaint_Info.ShenPiUser = txtShenPiDateEnd.Value;
                }

                dto_Complaint_Info.EndDate = txtEndDateBegin.Value;
                dto_Complaint_Info.BoHuiUser = txtEndDateEnd.Value == "" ? "" : Convert.ToDateTime(txtEndDateEnd.Value).AddDays(1).ToString("yyyy-MM-dd");
                if (txtEndDateBegin.Value == "" && txtEndDateEnd.Value != "")
                {
                    dto_Complaint_Info.BoHuiUser = txtEndDateEnd.Value;
                }

                DataTable dt = dao_Complaint_Info.Complaint_Agent_Percent(dto_Complaint_Info).Tables[0];

                StringBuilder sbTable = new StringBuilder();

                sbTable.Append("<table style=\"border:1px; border-color:Red;\"><tr>");

                for (int i = 1; i < dt.Columns.Count; i++)
                {
                    switch (dt.Columns[i].ColumnName)
                    {
                        case "AgentName":
                            sbTable.Append("<td>" + "经销商" + "</td>");
                            break;
                        case "Percent48":
                            sbTable.Append("<td>" + "48小时解决率" + "</td>");
                            break;
                        case "Percent72":
                            sbTable.Append("<td>" + "72小时解决率" + "</td>");
                            break;
                        case "Percent240":
                            sbTable.Append("<td>" + "10天解决率" + "</td>");
                            break;
                    }
                }
                sbTable.Append("</tr>");

                if (dt.Rows.Count > 0)
                {
                    for (int h = 0; h < dt.Rows.Count; h++)
                    {
                        sbTable.Append("<tr>");
                        for (int j = 1; j < dt.Columns.Count; j++)
                        {
                            sbTable.Append("<td>" + dt.Rows[h][j].ToString() + "</td>");
                        }
                        sbTable.Append("</tr>");
                    }
                }
                sbTable.Append("</table>");
                Response.Output.Write(sbTable);
                Response.Flush();
                Response.End();
            }
            catch (Exception ex)
            {
                Response.Write("<script language='javascript'>alert('" + ex.Message + "');</script>");
            } --------------------编程问答-------------------- http://download.csdn.net/detail/jx_521/5819725
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,