导出表到CSV文件列表 [英] export a list of table to CSV file

查看:271
本文介绍了导出表到CSV文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想表的列表导出到逗号分隔值(CSV),但没有得到正确的输出.OUTPUT从这个code来是HTML表格的形式。
这里是我的code,救救我....
谢谢

 公共无效ExportToCsv()
      {      DataClassesDataContext DB =新DataClassesDataContext();
      变种雇员= db.Employees.ToList();
      VAR电网=新System.Web.UI.WebControls.GridView();
      grid.DataSource =雇员;
      grid.DataBind();      StringBuilder的strbldr =新的StringBuilder();      的for(int i = 0; I< grid.Columns.Count;我++)
        {
            strbldr.Append(grid.Columns [I] .HeaderText +',');
        }
        对于(INT J = 0; J< grid.Rows.Count; J ++)
        {
            对于(INT K = 0; K< grid.Columns.Count; k ++)
            {
                //分离与逗号gridview的列
                strbldr.Append(grid.Rows [j]的.Cells [K]。文本+',');
            }
            //为附加行GridView的新生产线
            strbldr.Append(\\ n);
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader(内容处置,附件;文件名= YourFileName.csv);
        Response.ContentType =TEXT / CSV;
        StringWriter的SA =新的StringWriter(strbldr);
        HtmlTextWriter的HT =新的HtmlTextWriter(SA);
        grid.RenderControl(HT);
        的Response.Write(sa.ToString());
        到Response.End();
    }


解决方案

我觉得首先你的列表转换为数据表使用下面code

 公共静态数据表ToDataTable< T>(列表< T> l_oItems)
    {
        数据表oReturn =新的DataTable(typeof运算(T).Name点);
        [对象] a_oValues​​;
        INT I;        // ####收集有关通过T中的a_oProperties
        的PropertyInfo [] = a_oProperties typeof运算(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);        // ####遍历每个oProperty,.Add'ing每个.Name点/ .BaseType到我们oReturn价值
        // ####注:以.BaseType的调用是必需的DataTable作为/数据集不支持可空类型,所以它的不可为空的.Column定义对应类型是必需的
        的foreach(的PropertyInfo oProperty在a_oProperties)
        {
            oReturn.Columns.Add(oProperty.Name,BASETYPE(oProperty.PropertyType));
        }        // ####遍历l_oItems
        的foreach(T OITEM在l_oItems)
        {
            // ####采集这一循环a_oValues
            a_oValues​​ =新对象[a_oProperties.Length]            // ####遍历a_oProperties,填充每个a_oValues​​,因为我们去
            对于(i = 0; I< a_oProperties.Length;我++)
            {
                a_oValues​​ [I] = a_oProperties [I] .GetValue(OITEM,NULL);
            }            // ####。新增了重新presents的.Row当前a_oValues​​到我们oReturn价值
            oReturn.Rows.Add(a_oValues​​);
        }        // ####以上确定oReturn值返回给调用者
        返回oReturn;
    }    私有静态类型基本类型(类型oType)
    {
        // ####如果通过oType是有效的,.IsValueType是logicially空,获得(其)UnderlyingType
        如果(oType = NULL&放大器;!&安培; oType.IsValueType和放大器;&安培;
            oType.IsGenericType&功放;&安培; oType.GetGenericTypeDefinition()== typeof运算(可空<>)
        )
        {
            返回Nullable.GetUnderlyingType(oType);
        }
        // ####否则传递oType为空或不logicially空的,因此简单地返回传递oType
        其他
        {
            返回oType;
        }
    }

然后用低于code出口数据表到CSV ..

 公共静态字符串ToCSV(DataTable中的dataTable)
    {
        //创建一个能够容纳的数据的StringBuilder
        StringBuilder的SB =新的StringBuilder();
        //检查是否有在数据表中的列
        如果(dataTable.Columns.Count!= 0)
        {
            //环通为每头列
            的foreach(在dataTable.Columns的DataColumn列)
            {
                //追加列名,后跟分隔符
                sb.Append(column.ColumnName +,);
            }
            //添加回车
            sb.Append(\\ r \\ n);            //环通DataTable的每一行            的foreach(在dataTable.Rows的DataRow行)
            {
                //环通在数据表中的每一列
                的foreach(在dataTable.Columns的DataColumn列)
                {
                    //取得指定列上的列的值
                    //并追加分离器
                    sb.Append(\\+行[柱]的ToString()+\\+,);
                }
                //添加回车
                sb.Append(\\ r \\ n);
            }
        }
        返回(sb.ToString());
    }

主要功能是:这个

  DataTable的DT = GeneralFunctions.ToDataTable(HereputyourlistforcovertToDataTable);
                如果(DT!= NULL)
                {
                    如果(dt.Rows.Count大于0)
                    {
                        Response.Clear();
                        Response.ClearHeaders();
                        Response.ClearContent();
                        Response.ContentType =TEXT / CSV;
                        Response.AddHeader(内容处置,附件;文件名= ReceivingLog.csv);
                        的Response.Write(ToCSV(DT));
                        到Response.End();
                    }
                }

I am trying to export a list of table to comma-separated value(CSV) .but not getting the correct output .output coming from this code is in the form of html table. Here is my code,Help Me .... Thanks

      public void ExportToCsv()
      {

      DataClassesDataContext db = new DataClassesDataContext();
      var employee = db.Employees.ToList();
      var grid = new System.Web.UI.WebControls.GridView();
      grid.DataSource = employee;
      grid.DataBind();

      StringBuilder strbldr = new StringBuilder();

      for (int i = 0; i < grid.Columns.Count; i++)
        {
            strbldr.Append(grid.Columns[i].HeaderText + ',');
        }
        for (int j = 0; j < grid.Rows.Count; j++)
        {
            for (int k = 0; k < grid.Columns.Count; k++)
            {
                //separating gridview columns with comma
                strbldr.Append(grid.Rows[j].Cells[k].Text + ',');
            }
            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=YourFileName.csv");
        Response.ContentType = "text/csv";
        StringWriter sa = new StringWriter(strbldr);
        HtmlTextWriter ht = new HtmlTextWriter(sa);
        grid.RenderControl(ht);
        Response.Write(sa.ToString());
        Response.End();
    }

解决方案

I think First you convert your list to datatable by using below code

public static DataTable ToDataTable<T>(List<T> l_oItems)
    {
        DataTable oReturn = new DataTable(typeof(T).Name);
        object[] a_oValues;
        int i;

        //#### Collect the a_oProperties for the passed T
        PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        //#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
        //####     NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
        foreach (PropertyInfo oProperty in a_oProperties)
        {
            oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
        }

        //#### Traverse the l_oItems
        foreach (T oItem in l_oItems)
        {
            //#### Collect the a_oValues for this loop
            a_oValues = new object[a_oProperties.Length];

            //#### Traverse the a_oProperties, populating each a_oValues as we go
            for (i = 0; i < a_oProperties.Length; i++)
            {
                a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
            }

            //#### .Add the .Row that represents the current a_oValues into our oReturn value
            oReturn.Rows.Add(a_oValues);
        }

        //#### Return the above determined oReturn value to the caller
        return oReturn;
    }

    private static Type BaseType(Type oType)
    {
        //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
        if (oType != null && oType.IsValueType &&
            oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
        )
        {
            return Nullable.GetUnderlyingType(oType);
        }
        //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
        else
        {
            return oType;
        }
    }

Then Use below code for export datatable to csv..

public static string ToCSV(DataTable dataTable)
    {
        //create the stringbuilder that would hold the data
        StringBuilder sb = new StringBuilder();
        //check if there are columns in the datatable
        if (dataTable.Columns.Count != 0)
        {
            //loop thru each of the columns for headers
            foreach (DataColumn column in dataTable.Columns)
            {
                //append the column name followed by the separator
                sb.Append(column.ColumnName + ",");
            }
            //append a carriage return
            sb.Append("\r\n");

            //loop thru each row of the datatable

            foreach (DataRow row in dataTable.Rows)
            {
                //loop thru each column in the datatable
                foreach (DataColumn column in dataTable.Columns)
                {
                    //get the value for the row on the specified column
                    // and append the separator
                    sb.Append("\"" + row[column].ToString() + "\"" + ",");
                }
                //append a carriage return
                sb.Append("\r\n");
            }
        }
        return (sb.ToString());
    }

Main Function is : This

DataTable dt = GeneralFunctions.ToDataTable(HereputyourlistforcovertToDataTable);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        Response.Clear();
                        Response.ClearHeaders();
                        Response.ClearContent();
                        Response.ContentType = "text/CSV";
                        Response.AddHeader("content-disposition", "attachment; filename=ReceivingLog.csv");
                        Response.Write(ToCSV(dt));
                        Response.End();
                    }
                }

这篇关于导出表到CSV文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆