C# export generic data via Microsoft.Office.Interop.Excel vs NPOI,the latter is much faster 40 times than the former

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.IO;
using NPOI.XSSF.UserModel;

namespace Framework.Utility
{
    public class ExportHelper<T> where T : class, new()
    {
        public static void ExportDataViaOfficeInteropExcel(IEnumerable<T> dataList, ref string fileName, bool isAutoDownload = false)
        {
            int loopCount = 1;
            try
            {
                if (dataList == null || !dataList.Any())
                {
                    MessageBox.Show("The data source is null");
                    return;
                }
                var excelApp = new Excel.Application();
                var workBook = excelApp.Workbooks.Add();
                var workSheet = (Worksheet)workBook.Worksheets[1];
                workSheet.Columns.AutoFit();
                var firstRowData = dataList.FirstOrDefault();
                var pis = firstRowData.GetType().GetProperties().Where(x => !x.GetMethod.IsVirtual).ToArray();
                if (pis != null && pis.Any())
                {
                    for (int i = 0; i < pis.Count(); i++)
                    {
                        workSheet.Cells[1, i + 1] = pis[i].Name;
                    }

                    int row = 1;
                    foreach (var data in dataList)
                    {
                        row++;
                        for (int i = 0; i < pis.Count(); i++)
                        {
                            var objValue = pis[i].GetValue(data);
                            loopCount++;
                            workSheet.Cells[row, i + 1] = objValue?.ToString();
                        }
                    }
                }
                //SaveFileDialog sfd = new SaveFileDialog();
                //sfd.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                //sfd.FileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                //if (sfd.ShowDialog()==DialogResult.OK)
                //{                     
                //    workBook.SaveCopyAs(sfd.FileName);
                //}
                //string fileName= $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.xlsx"; 
                fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}InteropExcel.xlsx");
                workBook.SaveCopyAs(fileName);
                Console.WriteLine(loopCount);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
        }

        public static void ExportDataViaNPOI(List<T> dataList,ref string fileName)
        {
            if (dataList == null || !dataList.Any())
            {
                MessageBox.Show("The data source is null");
                return;
            }

            XSSFWorkbook book = new XSSFWorkbook();
            fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}NPOI.xlsx");
            var firstRowData = dataList.FirstOrDefault(); 
            var sheet = book.CreateSheet("Sheet1");
            var firstRow = sheet.CreateRow(0);
            var propertiesArr = firstRowData.GetType().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 <= dataList.Count; i++)
            {
                var indexRow = sheet.CreateRow(i);
                for (int j = 0; j < propertiesArr.Length; j++)
                {
                    var indexColumn = indexRow.CreateCell(j);
                    var indexColumnName = propertiesArr[j];
                    var columnValue = indexColumnName.GetValue(dataList[i - 1]);
                    if (columnValue != null)
                    {
                        indexColumn.SetCellValue(columnValue.ToString());
                    }
                }
            }
            using (FileStream stream = File.OpenWrite(fileName))
            {
                book.Write(stream);
                stream.Close();
            }
            dataList = null;
        }
    }
}

InteropExcel,202011302115526893,Count:1000,time cost 38261 milliseconds

NPOI,202011302116405231,Count:1000,time cost 823 milliseconds

posted @ 2020-11-30 20:24  FredGrit  阅读(116)  评论(0编辑  收藏  举报