如何摆脱数据表C#中的重复行

时间:2019-03-31 13:36:51

标签: c# excel datatable

我将一些数据导出到excel工作表,但是输出不符合预期

这是我要导出的对象:

public class EventsQuestionsAndAnswersVM
{
    public int FormId { get; set; }
    public string FormName { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
    public string ReportNumber { get; set; }
}

这是将我的对象转换为数据表的代码:

    public static DataTable ListToDataTable<T>(List<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable dataTable = new DataTable();

        for (int i = 0; i < properties.Count; i++)
        {
            PropertyDescriptor property = properties[i];
            dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
        }

        object[] values = new object[properties.Count];

        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = properties[i].GetValue(item);
            }

            dataTable.Rows.Add(values);
        }
        return dataTable;
    }

我希望采用以下形式:

1

但我有

1

0 个答案:

没有答案