C#使用MiniExcel操作Excel更快更高效(替代NPOI)

Posted on 2022-07-03 11:52  樱木007  阅读(5195)  评论(2编辑  收藏  举报

1.简介

    MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。目前主流框架如Npoi 需要将数据全载入到内存方便操作,但这会导致内存消耗问题。

MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。

2.特点

   低内存耗用,避免OOM(out of memoery)、频繁 Full GC 情况支持即时操作每行数据兼具搭配 LINQ 延迟查询特性,能办到低消耗、快速分页等复杂查询

轻量,不需要安装 Microsoft Office、COM+,DLL小于150KB简便操作的 API 风格。

3.使用

使用Nuget搜索Miniexcel安装

4.Demo 

使用winform程序做demo

准备一个测试的exlce文件test.xlsx,里面有三列数据,Id,Name,Title 

 

根据excel的内容定义一个类Test

 public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
    }

winform中添加两个按钮和一个DataGridView,主要代码如下:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            var openfiledialog = new OpenFileDialog();
            if (openfiledialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openfiledialog.FileName;
                var list = MiniExcel.Query<Test>(fileName).ToList();
                dataGridView1.DataSource = list;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "请选择文件路径";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string folder = folderBrowserDialog.SelectedPath;
                string fileName = Path.Combine(folder, "test1.xlsx");
                var data = dataGridView1.DataSource;
                var list = (List<Test>)data;
                var res = GetExcelList(list);
                MiniExcel.SaveAs(
                    path:fileName, 
                    value:res,
                    printHeader:true,
                    sheetName:"Sheet1",
                    excelType:ExcelType.UNKNOWN,
                    configuration:null,
                    overwriteFile:true);
                MessageBox.Show("导出成功!");
            }
            
        }

        /// <summary>
        /// 将数据源的标头改成中文表头
        /// </summary>
        /// <param name="test"></param>
        /// <returns></returns>

        private IEnumerable<Dictionary<string, object>> GetExcelList(List<Test> test)
        {
            foreach (var item in test)
            {
                var newCompanyPrepareds = new Dictionary<string, object>();
                newCompanyPrepareds.Add("Id", item.Id);
                newCompanyPrepareds.Add("姓名", item.Name);
                newCompanyPrepareds.Add("职位", item.Title);
                yield return newCompanyPrepareds;
            }
        }
    }

 

 

 

 

 

 

 

 

 参考:https://mp.weixin.qq.com/s/GXK4D0675CZP021cMZtnDA

 

 

Copyright © 2024 樱木007
Powered by .NET 8.0 on Kubernetes