c# - 将表格列表导出到 CSV 文件

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

最佳答案

我认为首先使用以下代码将列表转换为数据表

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

关于c# - 将表格列表导出到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8530655/

相关文章:

ASP.NET MVC Html.TextBox刷新问题

asp.net - 在 GridView 中最好放置模式弹出窗口的位置

java - C# 中的 Byte[]String 到 String

c# - WP7 中的加速度计问题

c# - Xamarin ContentView 构造函数

c# - UWP v10240 获取AccentColor

c# - 将字符串转换为日期时间

c# - 使用 LINQ 或 C# 清理字符串中特定 HTML 的算法

c# - 尝试使 View 模型项等于变量时出现空值错误

javascript - 如何使用 JavaScript 创建文本框 mask ?