泛型ListToExcelHelp类
需求:
在开发的时候,有ExcelHelp类,它的功能是datatable和excel之间的转换,
但是在C#entityframework实际开发的过程中,很容易拿到list,如果用ExcelHelp类的datatableToExcel方法,
需要先把list转换成datatable,这样就显得很麻烦,系统开销也打了。
解决方法:
所以在经过一番思考后决定写一个ListToExcelHelp类,由于list都是包含某个实体具体的类,所以还要给这个类添加一个泛型接口。
下面是经过一番血战写出的代码,大神请路过。。。当然还有些Excel写数据不仅仅是把一些文本数据,还包括一个样式,数据有效性等等的操作,这里
我就没有贴出来,会影响读者的耐心。
下面是代码:
public class DownLoadHelp<T> where T : class
{
private string clounmNames { get; set; }
private string fileName = null; //文件名
private string filePath = null;
private IWorkbook workbook = null;
private FileStream fs = null;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="clounmnames">列名</param>
/// <param name="filename">文件名</param>
/// <param name="filepath">路径名</param>
public DownLoadHelp(string clounmnames, string filename, string filepath)
{
this.clounmNames = clounmnames;
this.fileName = filename;
this.filePath = filepath;
}
/// <summary>
///
/// </summary>
/// <param name="list"></param>
/// <param name="sheetName"></param>
/// <param name="isColumnWritten"></param>
/// <param name="fields"></param>
/// <returns></returns>
public int ListToExcel(List<T> list, string sheetName, bool isColumnWritten, string fields)
{
List<string> cns = new List<string>();
cns = clounmNames.Split(',').ToList();
List<string> fls = new List<string>();
fls = fields.Split(',').ToList();
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//CellRangeAddressList regions = new CellRangeAddressList(x, y, x1, y1);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook();
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook();
}
//try
//{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < cns.Count; ++j)
{
row.CreateCell(j).SetCellValue(cns[j]);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < list.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < fls.Count; ++j)
{
string str = list[i].GetType().GetProperty(fls[j]).GetValue(list[i], null).ToString();
row.CreateCell(j).SetCellValue(str);
}
++count;
}
workbook.Write(fs); //写入到excel
fs.Close();
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
}
有了这类就方便很多啦~
浙公网安备 33010602011771号