将表列表导出为CSV文件

时间:2011-12-16 06:38:38

标签: c# asp.net

我正在尝试将表的列表导出为逗号分隔值(CSV)。但是没有得到正确的输出。来自此代码的输出是以html表的形式。 这是我的代码,帮助我.... 感谢

      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();
    }

1 个答案:

答案 0 :(得分:0)

我认为首先使用下面的代码

将列表转换为数据表
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;
        }
    }

然后使用以下代码将数据表导出到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());
    }

主要功能是:这个

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();
                    }
                }