C#,NPOI,Export Generic Data

2021-06-22 13:07

阅读:577

标签: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(storeArr);
Store[] arr = db.Stores.ToArray();
ExportTEntity(arr);
}

Console.ReadLine();
}

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

using (SaveFileDialog sfd = new SaveFileDialog())
{
List columnsList = new List();
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 {
var column = firstRow.CreateCell(i);
column.SetCellValue(propertiesArr[i].Name);
}

for (int i = 1; i {
var indexRow = sheet.CreateRow(i);
for (int j = 0; 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


评论


亲,登录后才可以留言!