学无先后,达者为师

网站首页 编程语言 正文

C# 利用ExcelDataReader 读取excel文件

作者:文哥打酱油 更新时间: 2022-04-17 编程语言

github地址 https://github.com/exceldatareader/exceldatareader

1.在NuGet中输入excel搜索,点击安装这两个如图

2.新建一个类,写入代码

    class ExcelReader 
    {
        public List> getData(string filePath)
        {
            List> list = new List>();
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                // Auto-detect format, supports:
                //  - Binary Excel files (2.0-2003 format; *.xls)
                //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var configuration = new ExcelDataSetConfiguration { ConfigureDataTable = tableReader => new ExcelDataTableConfiguration { UseHeaderRow = true } };
                    DataSet result = reader.AsDataSet(configuration);
                    for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                    {
                        Dictionary dict = new Dictionary();
                        for (int j = 0; j < result.Tables[0].Columns.Count; j++)
                        {
                            dict.Add(result.Tables[0].Columns[j].ColumnName, result.Tables[0].Rows[i][j]);
                        }
                        list.Add(dict);
                    }
                }
            }
            return list;
        }
    }

 

原文链接:https://blog.csdn.net/zxw75192/article/details/113406767

栏目分类
最近更新