如何为列表中的每个项创建单独的DataTable [英] How to create separate DataTable for every item in list

查看:59
本文介绍了如何为列表中的每个项创建单独的DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我的代码中有字符串列表,我想为列表中的每个项目创建一个数据表。



为此,我已经完成了以下代码。但它没有用。

Hi I am having string list in my code and I want to create a Data Table for every item present in the list.

For that I have done the following code. but its not working.

//below is the code where doc is WorKbook object

Microsoft.Office.Interop.Excel.Sheets workSheets = doc.Worksheets;

 for (int i = 1; i <= list.Count; i++)
 {
  
  var xlsNewSheet = (Microsoft.Office.Interop.Excel.Worksheet)workSheets.Add(Missing.Value, workSheets[i], Missing.Value, Missing.Value);
                            
                            xlsNewSheet.Name = i + "of" + list.Count;
                            System.Data.DataTable table = TODataTable<string>(list[i]); //its giving error here    
                        }
}
                        


//And here is the definition of TODataTable function






//code to convert list to datatable
        public static System.Data.DataTable TODataTable<string>(List<string> items)
        {

            System.Data.DataTable datatable = new System.Data.DataTable(typeof(string).Name);
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo pro in Props)
            {
                datatable.Columns.Add(pro.Name);
            }
            foreach (string 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;
        }





问:我的代码中有什么问题,应该采用什么方法?



Q-what is the problem in my code and what should be correct way?

推荐答案

试试这里:转换列表到DataTable [ ^ ]

可能,您的列表集合不是字符串数组,但是您没有显示定义它的代码。



该链接提供了一个可以处理任何对象集合的方法,并且可以与您的对象一起使用。
Try having a look here: Converting a List to a DataTable[^]
Probably, your list collection is not an array of strings, but you don't show the code defining it.

The link gives a method that will work with any collection of objects, and should work with yours.


这篇关于如何为列表中的每个项创建单独的DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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