Use NPOI to operate Excel in .Net7

The following introduces how .net7 simply uses NPOI to read Excel tables. NPOI refers to a program built on POI 3.x version. NPOI can read and write Word or Excel documents without installing Office. NPOI is a good old-fashioned control, and it can be realized with only a small amount of code. The following is a step-by-step implementation.

1. Environmental preparation

1. Create a new console program

 

2. Name it NPOIExcel

3. Select .NET7, here "do not use top-level statements"

4. Right-click on the project, find the management Nuget and click to enter, nuget management, enter NPOI search, select DotNetCore.NPOI, and click Install. Or install with nuget code.

Code installation method:

PM> Install-Package DotNetCore.NPOI

2. Code writing

Write the following code in Program.cs, and there are specific steps in the code

using NPOI.SS.UserModel;//必须引用
       static void Main(string[] args)
        {
            //声明文件路径字段,存储文件路径对应目标文件
            var fileName = @"d:\npoireadExcel.xlsx";
            //判断文件是否存在,否则会报错
            if (!File.Exists(fileName))
            {
                return;
            }
            //根据上面路径读取文件
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            //根据文件流创建excel数据结构
            IWorkbook workbook = WorkbookFactory.Create(fs);

            //尝试获取Excel第一个sheet 
            var sheet = workbook.GetSheetAt(0);
            //判断是否获取到 sheet 
            if (sheet != null)
            {
                //获取第一行 这里可以搞个while循环多行,判断没有数据为止
                var row = sheet.GetRow(0);
                for (int i = 0; i < row.Count(); i++)
                {
                    //输出每个单元格的数据
                    Console.WriteLine($"第一行数据:第 {i} 个数据值:{row.GetCell(i).ToString()}");
                }
            }
        }

 

3. Display results

Create a new Excel file named npoireadExcel on the D drive, and enter the content in the first line, as shown in the figure below

The read data is as follows:

Summarize

The above describes the simple use of NPOI to read Excel files in .Net7, and shows the operation process and code writing step by step. Of course, the specific use scenario needs to be determined according to the situation of the project, this article is for reference only

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130833197