码迷,mamicode.com
首页 > Windows程序 > 详细

C#,NPOI,Export Generic Data

时间:2019-01-02 23:33:58      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:mes   sar   ==   store   stat   ret   sheet   mod   files   

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

标签:mes   sar   ==   store   stat   ret   sheet   mod   files   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!