/// <summary>
/// 导出excle文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="filePath"></param>
/// <param name="sheetName"></param>
public static void WriteExcel<T>(List<T> list, string filePath, string sheetName)
{
try
{
if (!string.IsNullOrEmpty(filePath) && null != list && list.Count > 0)
{
NPOI.SS.UserModel.IWorkbook book;
NPOI.SS.UserModel.ISheet sheet;
if (filePath.EndsWith(".xlsx"))
{
book = new NPOI.XSSF.UserModel.XSSFWorkbook();
sheet = book.CreateSheet(sheetName);
}
else
{
book = new NPOI.HSSF.UserModel.HSSFWorkbook();
sheet = book.CreateSheet(sheetName);
}
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
Type itemType = typeof(T);
System.Reflection.PropertyInfo[] itemPropertyies = itemType.GetProperties();
for (int i = 0; i < itemPropertyies.Length; i++)
{
var attribute = itemPropertyies[i].GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single();
row.CreateCell(i).SetCellValue(attribute.DisplayName);
}
for (int i = 0; i < list.Count; i++)
{
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
for (int j = 0; j < itemPropertyies.Length; j++)
{
row2.CreateCell(j).SetCellValue(Convert.ToString(itemPropertyies[j].GetValue(list[i])));
}
}
// 写入到客户端
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
book.Write(ms);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
book = null;
}
}
}
catch (Exception ex)
{
MessageBox.Show("写入excel时报错:" + ex.Message);
}
}