导出 IEnumerable;到 Excel

发布于 2024-09-11 10:01:28 字数 1539 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

归途 2024-09-18 10:01:28

下面的代码是我用来将 IEnumerable 转换为 DataTable 的代码,其中包含为每个属性命名的列,以及 IEnumerable 中每个项目的值(作为行)。从这里到将其保存为 CSV 文件只需很小的一步,

public class IEnumerableToDataTable
{
    public  static DataTable CreateDataTableForPropertiesOfType<T>()
    {
        DataTable dt = new DataTable();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (PropertyInfo pi in piT)
        {
            Type propertyType = null;
            if (pi.PropertyType.IsGenericType)
            {
                propertyType = pi.PropertyType.GetGenericArguments()[0];
            }
            else
            {
                propertyType = pi.PropertyType;
            }
            DataColumn dc = new DataColumn(pi.Name, propertyType);

            if (pi.CanRead)
            {
                dt.Columns.Add(dc);
            }
        }

        return dt;
    }

    public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        var table = CreateDataTableForPropertiesOfType<T>();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (var item in items)
        {
            var dr = table.NewRow();

            for (int property = 0; property < table.Columns.Count; property++)
            {
                if (piT[property].CanRead)
                {
                    dr[property] = piT[property].GetValue(item, null);
                }
            }

            table.Rows.Add(dr);
        }
        return table;
    }
}

因此,您可以编写以下代码将数据转换为数据表:

IEnumerable<Thing> values = GetMyIEnumerableValues();

var tableOfData = IEnumerableToDataTable.ToDataTable(values);

一旦它存在,将其写入 CSV 文件或任何其他格式的文件是相当简单的您的选择,因为从 IEnumerable 中提取数据的所有“棘手”反射工作都已完成。

The code below is code I use to convert an IEnumerable<T> to a DataTable containing columns named for each property, along with the values of each item in the IEnumerable as rows. It's a very small hop from this to saving it as a CSV file

public class IEnumerableToDataTable
{
    public  static DataTable CreateDataTableForPropertiesOfType<T>()
    {
        DataTable dt = new DataTable();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (PropertyInfo pi in piT)
        {
            Type propertyType = null;
            if (pi.PropertyType.IsGenericType)
            {
                propertyType = pi.PropertyType.GetGenericArguments()[0];
            }
            else
            {
                propertyType = pi.PropertyType;
            }
            DataColumn dc = new DataColumn(pi.Name, propertyType);

            if (pi.CanRead)
            {
                dt.Columns.Add(dc);
            }
        }

        return dt;
    }

    public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        var table = CreateDataTableForPropertiesOfType<T>();
        PropertyInfo[] piT = typeof(T).GetProperties();

        foreach (var item in items)
        {
            var dr = table.NewRow();

            for (int property = 0; property < table.Columns.Count; property++)
            {
                if (piT[property].CanRead)
                {
                    dr[property] = piT[property].GetValue(item, null);
                }
            }

            table.Rows.Add(dr);
        }
        return table;
    }
}

So, you could write the following to convert your data to a datatable:

IEnumerable<Thing> values = GetMyIEnumerableValues();

var tableOfData = IEnumerableToDataTable.ToDataTable(values);

Once it's there, it's fairly trivial to write it out to a CSV file, or any other format of your choice, as all the "tricky" reflection work to extract the data from the IEnumerable<T> has been done.

楠木可依 2024-09-18 10:01:28

我已经解决了与你所问的类似的问题。就像你有一个 IEnumerable

IEnumerable<TaskSheetHead> taskSheetHead =
    new TaskSheetHeadService().GetEmployeeTimesheet(entity);

所以,如果你想从中创建一个 Excel,只需创建一个工作簿

var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet();

并使用循环进行迭代,然后将其添加到工作表

foreach(TaskSheetHead taskSheethead in taskSheetHead) 
{
    //decimal totalTask = decimal.Zero;
    //double totalTime = 0;

    foreach(TaskSheet taskSheet in taskSheethead.TaskSheets) 
    {
        var row2 = sheet.CreateRow(rowNumber++);
        
        row2.CreateCell(0).SetCellValue(taskSheethead.Date.ToString("MMMM dd, yyyy"));
        row2.CreateCell(1).SetCellValue(taskSheet.Task.Project.ProjectName + ":" + taskSheet.Task.Title + "-" + taskSheet.Comment);
        
        row2.CreateCell(2).SetCellValue(taskSheet.ExpendedHour);
        row2.CreateCell(3).SetCellValue(taskSheet.IsBilledToClient);
        //totalTask += 1;
        //totalTime += taskSheet.ExpendedHour;
    }
    
    var row3 = sheet.CreateRow(rowNumber++);
    
    row3.CreateCell(0).SetCellValue("");
    row3.CreateCell(1).SetCellValue("");
    row3.CreateCell(2).SetCellValue("");
    row3.CreateCell(3).SetCellValue("");

}

这里我有另一个子列表,因此我使用内部循环进行迭代。按照你的选择去做。

I have solved a problem similar to what you asked. Like you have an IEnumerable

IEnumerable<TaskSheetHead> taskSheetHead =
    new TaskSheetHeadService().GetEmployeeTimesheet(entity);

So if you want to make a excel from this just create a workbook

var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet();

And iterate with a looping and then add it to the worksheet

foreach(TaskSheetHead taskSheethead in taskSheetHead) 
{
    //decimal totalTask = decimal.Zero;
    //double totalTime = 0;

    foreach(TaskSheet taskSheet in taskSheethead.TaskSheets) 
    {
        var row2 = sheet.CreateRow(rowNumber++);
        
        row2.CreateCell(0).SetCellValue(taskSheethead.Date.ToString("MMMM dd, yyyy"));
        row2.CreateCell(1).SetCellValue(taskSheet.Task.Project.ProjectName + ":" + taskSheet.Task.Title + "-" + taskSheet.Comment);
        
        row2.CreateCell(2).SetCellValue(taskSheet.ExpendedHour);
        row2.CreateCell(3).SetCellValue(taskSheet.IsBilledToClient);
        //totalTask += 1;
        //totalTime += taskSheet.ExpendedHour;
    }
    
    var row3 = sheet.CreateRow(rowNumber++);
    
    row3.CreateCell(0).SetCellValue("");
    row3.CreateCell(1).SetCellValue("");
    row3.CreateCell(2).SetCellValue("");
    row3.CreateCell(3).SetCellValue("");

}

Here I have another child list, therefore I have iterated using a inner loop. Do as your choice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文