最近在使用spire,记录一些使用方法和遇到的问题。
使用文档点击跳转
注意事项:
1.spire.xls 和 spire的其他模块如:spire.pdf 不能同时在一个项目里使用,可安装spire.office来解决这一问题。
2.spire.xls 使用中Workbook workbook = new Workbook();报错。检查是否当前包的版本是否支持.net core 5.0 。可右击包,更新选择别的版本尝试。
public string CreateSpireXls(List<T> data)
{
//设置文件保存路径
string fileName = Guid.NewGuid().ToString() + ".xlsx";
fileName = "D:\\" + fileName;
//创建一个workbook对象,默认创建03版的Excel
Workbook workbook = new Workbook();
//指定版本信息,07及以上版本最多可以插入1048576行数据
workbook.Version = ExcelVersion.Version2010;
//获取第一张sheet
Worksheet sheet = workbook.Worksheets[0];
DataTable dt = ToDataTable(data);
//得到在datatable里的数据
// (DataTable)list;
//从第一行第一列开始插入数据,true代表数据包含列名
sheet.InsertDataTable(dt, true, 1, 1);
//保存文件
workbook.SaveToFile(fileName, ExcelVersion.Version2010);
return fileName;
}
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
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);
}
tb.Rows.Add(values);
}
return tb;
}
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}