将IList <T>或IQueryable <T>保存到Excel是一个常见的需求,以下是一个简单的方法,使用C#编写,将IList <T>或IQueryable <T>保存到Excel文件中。
首先,需要安装以下NuGet包:
安装完成后,可以使用以下代码将IList <T>或IQueryable <T>保存到Excel文件中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ClosedXML.Excel;
public static class ExcelExtensions
{
public static void ToExcel<T>(this IList<T> list, string filePath)
{
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance);
using var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sheet1");
// 写入表头
var colIndex = 1;
foreach (var property in properties)
{
worksheet.Cell(1, colIndex).Value = property.Name;
colIndex++;
}
foreach (var field in fields)
{
worksheet.Cell(1, colIndex).Value = field.Name;
colIndex++;
}
// 写入数据
for (var rowIndex = 0; rowIndex< list.Count; rowIndex++)
{
var item = list[rowIndex];
colIndex = 1;
foreach (var property in properties)
{
worksheet.Cell(rowIndex + 2, colIndex).Value = property.GetValue(item);
colIndex++;
}
foreach (var field in fields)
{
worksheet.Cell(rowIndex + 2, colIndex).Value = field.GetValue(item);
colIndex++;
}
}
workbook.SaveAs(filePath);
}
}
使用方法:
var list = new List<Person>();
// 添加数据
list.ToExcel("output.xlsx");
其中,Person是一个简单的类,包含一些属性和字段,例如:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
这样,就可以将IList <T>或IQueryable <T>保存到Excel文件中了。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云