21xz

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelLibrary;
using ExcelLibrary.SpreadSheet;
using System.Reflection;
using System.Collections;

namespace CommTool
{
/// <summary>
#region 这一段代码没用,但是请不要删除,因为这里体现了一些数据类型显示的方法思想,要懂得举一反三,这里面还是有值得学习和参考的东西的
//worksheet.Cells[0, 1] = new Cell((short)1);
//worksheet.Cells[2, 0] = new Cell(9999999);
//worksheet.Cells[3, 3] = new Cell((decimal)3.45);
//worksheet.Cells[2, 2] = new Cell("Text string");
//worksheet.Cells[2, 4] = new Cell("Second string");
//worksheet.Cells[4, 0] = new Cell(32764.5, "#,##0.00");
//worksheet.Cells[5, 1] = new Cell(DateTime.Now, @"YYYY\-MM\-DD");
#endregion
/// </summary>
public static class ExcelCommCreate
{
private static int minrows = 30;
public static string CreateExcelFile<T>(string phypath, List<T> source)
{
string filename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls";
string tempfile = phypath + filename;
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("Sheet1");
//读取属性,填充表头
PropertyInfo[] properties = typeof(T).GetProperties();
int orders = 0;
foreach (PropertyInfo item in properties)
{
worksheet.Cells[0, orders] = new Cell(item.Name);
orders++;
}

int row = 1;
int cloum = 0;
foreach (T entity in source)
{
cloum = 0;
foreach (PropertyInfo item in properties)
{
//如果是日期格式要特别处理一下
if(item.PropertyType == typeof(DateTime))
{
worksheet.Cells[row, cloum] = new Cell(item.GetValue(entity, null), @"YYYY\-MM\-DD");
}
else
worksheet.Cells[row, cloum] = new Cell(item.GetValue(entity,null));
cloum++;
}
row++;
}

//判断下是否达到最小标准,没有填充空.因为不填充空,会有格式有问题的提示
if (row < minrows)
{
for (int i = row; i <= minrows; i++)
{
for (int j = 0; j < orders; j++)
{
worksheet.Cells[i, j] = new Cell("");
}
}
}

//操作完成,保存一下
workbook.Worksheets.Add(worksheet);
workbook.Save(tempfile);
return filename;
}
}
}

分类:

技术点:

相关文章:

  • 2021-12-08
  • 2021-11-01
  • 2021-10-17
  • 2021-10-11
  • 2021-04-11
  • 2021-08-24
  • 2021-06-05
  • 2021-10-16
猜你喜欢
  • 2021-09-15
  • 2021-09-01
  • 2021-11-23
  • 2021-12-08
  • 2021-08-31
  • 2021-05-07
  • 2021-09-11
相关资源
相似解决方案