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

原文链接: https://www.cnblogs.com/Fred1987/p/14063402.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/401889

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:28
下一篇 2023年4月19日 上午9:28

相关推荐