NPOI Chapter 2-Create an excel

Introduce NPOI

Use NuGet to add NPOI
Insert picture description here
Insert picture description here

Introducing namespace

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
This is the namespace that must be introduced to create *.xlsx files. The namespace that the .xls file needs to reference is different from that of the .xlsx file. I will talk about this later. Today, I will take xlsx as an example.
Insert picture description here

Realize the creation of C:\test.slsx file

####### Look at the code directly

/// <summary>
        /// 使用npoi创建一个excel文件
        /// </summary>
        public void NPOICreateExcel()
        {
    
    
            //声明一个工作簿
            XSSFWorkbook workBook = new XSSFWorkbook();
            //创建一个sheet页
            ISheet sheet= workBook.CreateSheet("MySheet");
            //向第一行第一列的单元格添加文本“老王的demo”

            IRow row= sheet.GetRow(0);//获取第一行
            if (row==null)//workbook 创建的sheet里是获取不到对应的excel行和列的单元格对象
            {
    
    
                row= sheet.CreateRow(0);
            }
            ICell cell= row.GetCell(0);//获取第一列
            if (cell==null)
            {
    
    
                cell= row.CreateCell(0);
            }
            cell.SetCellValue("老王的Demo");

            //输出excel文件
            using (FileStream fs = File.OpenWrite("C:\\text.xlsx"))
            {
    
    
                workBook.Write(fs);//向打开的这个xls文件中写入并保存。
            }
        }

Effect after execution:
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39541254/article/details/106343728