c#经常会用到导出excel。
ClosedXML是一个.NET库,用于读取,操作和写入Excel 2007+(.xlsx,.xlsm)文件。它旨在提供一个直观且用户友好的interface来处理基础的OpenXML API。
ClosedXML许可证是MIT
。
示例:
using ClosedXML.Excel;
using DoExcel.Models;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.IO;
namespace DoExcel
{
class Program
{
static void Main(string[] args)
{
List<User> list = new List<User>() {
new User{ Name="Tom", Age=23 },
new User{ Name="Jack", Age=25 },
new User{ Name="Alice", Age=20 },
new User{ Name="Jan", Age=24 },
};
Dictionary<string, string> map = new Dictionary<string, string>() {
{"Name","姓名" },
{"Age","年龄" },
};
File.WriteAllBytes("demo.xlsx", GetExcel(list, map, true));
}
private static byte[] GetExcel<T>(List<T> list, Dictionary<string, string> columnMap, bool useOrderNo = true)
{
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("sheet1");
var propertyMap = typeof(T).GetProperties().ToDictionary(t => t.Name, t => t);
int columnNum = 1;
if (useOrderNo)
{
worksheet.Cell(1, columnNum++).Value = "序号";
}
foreach (var item in columnMap)
{
worksheet.Cell(1, columnNum++).Value = item.Value;
}
int row = 2;
for (int i = 0; i < list.Count; i++, row++)
{
var item = list[i];
int col = 1;
if (useOrderNo)
{
worksheet.Cell(row, col++).Value = i;
}
foreach (var column in columnMap)
{
worksheet.Cell(row, col++).Value = propertyMap[column.Key].GetValue(item);
}
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
return stream.ToArray();
}
}
}
}
}
需要注意的是Cell的行和列开始Index是1。在使用中遇到如下错误:
Row number must be between 1 and 1048576
Column number must be between 1 and 16384
由此可知,1<=行数<=1048576,1<=列数<=16384。