using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CJCMS.Contracts.DTO
{
public class PrintSortAttribute : Attribute
{
public int Sort { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using CJCMS.Contracts.DTO;
namespace CJCMS.Web.Company
{
public class ExcelHelper<T>
{
string SavePath = null;
HSSFWorkbook hssfworkbook;
public ExcelHelper(string templateFile, string savePath)
{
InitializeWorkbook(templateFile);
SavePath = savePath;
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="templateFile">模板路径</param>
void InitializeWorkbook(string templateFile)
{
FileStream file = new FileStream(templateFile, FileMode.Open);
hssfworkbook = new HSSFWorkbook(file);
file.Close();
}
public void AddRow(string sheetName, T t, int rowPosition)
{
ISheet tb = hssfworkbook.GetSheet(sheetName);
IRow row = tb.GetRow(rowPosition);
if (row == null)
{
row = tb.CreateRow(rowPosition);
}
foreach (System.Reflection.PropertyInfo p in t.GetType().GetProperties())
{
PrintSortAttribute sortAttr = (PrintSortAttribute)Attribute.GetCustomAttribute(p, typeof(PrintSortAttribute));
ICell cell = row.GetCell(sortAttr.Sort);
if (cell == null)
{
cell = row.CreateCell(sortAttr.Sort);
}
cell.SetCellValue(p.GetValue(t, null).ToString());
}
}
public void SetCellValue(string sheetName, int rowPosition, int columnPositon, string value)
{
ISheet tb = hssfworkbook.GetSheet(sheetName);
//创建一行,此行为第二行
IRow row = tb.GetRow(rowPosition);
if (row == null)
{
row = tb.CreateRow(rowPosition);
}
ICell cell = row.GetCell(columnPositon);
if (cell == null)
{
cell = row.CreateCell(columnPositon);
}
cell.SetCellValue(value);
}
public void WriteToFile()
{
FileStream file = new FileStream(SavePath + Guid.NewGuid().ToString() + ".xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
}
}
}