0

我有对象列表,我将它们转换为数据表,现在我无法将它们导出到 excel

下面是示例代码

class Program
{
    static void Main(string[] args)
    {
        Student s1 = new Student("Student-A",100);
        Student s2 = new Student("Student-B", 90);
        Student s3 = new Student("Student-C", 80);

        List<Student> studentList = new List<Student>() { s1,s2,s3};

        ListToDataTable converter = new ListToDataTable();
        DataTable dt = converter.ToDataTable(studentList);

        Console.WriteLine();
    }
}

下面是具有两个属性的学生类

    class Student
{
    public string Name { get; set; }
    public int? Score { get; set; }

    public Student(string name,int? score)
    {
        this.Name = name;
        this.Score = score;
    }
}

下面是用于将对象列表转换为数据表的类

public class ListToDataTable
{
    public DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);            
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {                
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {                    
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }

        return dataTable;
    }
}
4

3 回答 3

0

尝试从您的 DataTable 创建一个简单的 CSV 文件。

于 2013-06-10T13:43:38.190 回答
0

将列表转换为 DataTable 后,您可以使用以下 DataTable 扩展。

        public static string ToCSV(this DataTable table)
    {
        var result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }

用法示例:

        // replace with your data table here
        DataTable dt = new DataTable();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(dt.ToCSV());
        MemoryStream stream = new MemoryStream(bytes);
        StreamReader reader = new StreamReader(stream);
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename")); 
        Response.ContentType = "application/text";
        Response.ContentEncoding = Encoding.Unicode;
        Response.Output.Write(reader.ReadToEnd());
        Response.Flush();
        Response.End(); 
于 2013-06-10T13:43:51.953 回答
0

由于您已将其标记为互操作,因此我走那条路(无需创建 csv 文件,只需直接导出到 excel)。

这个解决方案不是最漂亮的,但它确实有效。我还对其进行了一些更改,因为您可以将 studentList 直接导出到 excel(无需先将其转换为 dataTable)。

首先,在您的解决方案中,您需要添加对“Microsoft.Office.Interop.Excel”的引用。为此,请在解决方案资源管理器中右键单击“引用”,然后单击“添加引用”,然后单击“.NET”选项卡,然后向下滚动以找到它。

完成后,按如下方式更新您的代码:

using System;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;

static void Main()
    {
        var s1 = new Student("Student-A", 100);
        var s2 = new Student("Student-B", 90);
        var s3 = new Student("Student-C", 80);

        var studentList = new List<Student> { s1, s2, s3 };

        // Create an excel sheet
        var xlApp = new Excel.Application { Visible = true };           // Create instance of Excel and make it visible.
        xlApp.Workbooks.Add(Excel.XlSheetType.xlWorksheet);             // Create a workbook (WB)
        var xlWS = (Excel.Worksheet)xlApp.ActiveSheet;                  // Reference the active worksheet (WS)
        xlWS.Name = "Exported Student";                                 // Name the worksheet

        // Add Header fields to Excel [row, column]
        var r = 1;
        xlWS.Cells[r, 1] = "Name";
        xlWS.Cells[r, 2] = "Score";

        // Copy data from StudentList to Excel
        foreach (Student student in studentList)
        {
            r++;
            xlWS.Cells[r, 1] = student.Name;
            xlWS.Cells[r, 2] = student.Score;
        }

    }

这将自动将您的 studentList 导出到 Excel 工作表。不需要 ListToDataTable 类。

于 2013-06-11T16:01:07.757 回答