首页 > Windows开发 > 详细

C#,NPOI,Export Generic Data

时间:2019-01-02 22:40:01      阅读:176      评论:0      收藏:0      [点我收藏+]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;

[STAThread]
static void Main(string[] args)
{
using (AdventureWorks2017Entities db = new AdventureWorks2017Entities())
{
//SalesOrderDetail[] storeArr = db.SalesOrderDetails.ToArray();
//ExportTEntity<SalesOrderDetail>(storeArr);
Store[] arr = db.Stores.ToArray();
ExportTEntity<Store>(arr);
}

Console.ReadLine();
}

static void ExportTEntity<T>(T [] arr)
{
if(arr!=null && !arr.Any())
{
return;
}

using (SaveFileDialog sfd = new SaveFileDialog())
{
List<string> columnsList = new List<string>();
HSSFWorkbook book;
string savedExcelFileName;
sfd.Filter = "Excel Files(.xls)|*.xls|Excel Files(.xlsx)| *.xlsx | All Files | *.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
book = new HSSFWorkbook();
var sheet = book.CreateSheet("Sheet1");
savedExcelFileName = sfd.FileName;
var firstRow = sheet.CreateRow(0);


var propertiesArr = typeof(T).GetProperties().Where(x => !x.GetMethod.IsVirtual).ToArray();
for (int i = 0; i < propertiesArr.Length; i++)
{
var column = firstRow.CreateCell(i);
column.SetCellValue(propertiesArr[i].Name);
}

for (int i = 1; i <= arr.Length; i++)
{
var indexRow = sheet.CreateRow(i);
for (int j = 0; j < propertiesArr.Length; j++)
{
var indexColumn = indexRow.CreateCell(j);
var columnValue = arr[i - 1].GetType().GetProperties().Where(x => !x.GetMethod.IsVirtual).ToArray()[j].GetValue(arr[i - 1]).ToString();

indexColumn.SetCellValue(columnValue);
}
}

using (var excelStream = new FileStream(savedExcelFileName, FileMode.Create, FileAccess.ReadWrite))
{
book.Write(excelStream);
excelStream.Close();
}

System.Windows.Forms.MessageBox.Show("Completed!");
}
}
}

C#,NPOI,Export Generic Data

原文:https://www.cnblogs.com/Fred1987/p/10211619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!