NPOI 创建Excel,数据读取与写入


<1>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using System.IO;
using System.Text;


namespace 导入导出Excel
{
    /// <summary>
    /// Excel导入导出 的摘要说明
    /// </summary>
    public class Excel导入导出 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/x-excel";

            //------------------------------------------创建Excel,并将数据写入--------  



            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个Excel文件    

            ISheet sheet = workbook.CreateSheet("Sheet1");//创建一个页   

            IRow row = sheet.CreateRow(0); //创建sheet页的第0行(索引从0开始)    

          
            row.CreateCell(0, CellType.String).SetCellValue("C罩杯");//创建第0行第0列string类型表格,并赋值"A罩杯"
            row.CreateCell(1, CellType.String).SetCellValue("D罩杯");//创建第0行第1列string类型表格,并赋值"B罩杯"
            row.CreateCell(2, CellType.String).SetCellValue("A罩杯");//创建第0行第2列string类型表格,并赋值"C罩杯"
            row.CreateCell(3, CellType.String).SetCellValue("F罩杯");//创建第0行第3列string类型表格,并赋值"D罩杯"
            row.CreateCell(18, CellType.Numeric).SetCellValue(5);  //创建第0行第17列Numeric类型表格,并赋值5

            //得到一个excel.xls文件的文件流 【开打指定路径下的文件,如果文件不存在则创建文件,并打开,以进行写入】    
            using (Stream stream = File.OpenWrite("d:/excel.xls"))
            {

                workbook.Write(stream); //将这个workbook文件写入到stream流中
            }






            //------------------------------------------读取Excel的数据-------------  


            using (Stream stream1 = File.OpenRead("d:/excel.xls"))
            {

                //读取workbook这个工作薄的第0个Sheet(GetSheetAt(0)),第0行(GetRow(0)),第0格(GetCell(0))的值                 
                //string s = workbook.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue;  

                int cellRows = sheet.LastRowNum;

                //获取workbook中sheet页的最后一行的行号【行号从0开始】
                int sheetRowCount = sheet.LastRowNum;

                //这个循环是获取shee1页中"所有的行中"具有"最多列"的"列数"
                int maxCellCount = 0;
                for (int i = sheet.FirstRowNum; i <= cellRows; i++) //遍历sheet页的所有的行
                {
                    row = sheet.GetRow(i); //获取当前行
                    if (row == null) 这一句很关键,因为没有数据的行默认是null 
                    {
                        continue; //既然当前行无数据那就结束本次循环,进行下次循环
                    }
                    else
                    {
                        int cellCount = row.LastCellNum;  //获取当前行的列数
                        if (cellCount > maxCellCount)    //如果当前行的列数大于"最大列数maxCellCount",那么我就将当前行的列数设置为最大的列数
                        {
                            maxCellCount = cellCount;  //for循环结束后,maxCellCount就得到了"所有的行中"具有"最多列"的"列数"
                        }
                    }
                }






                //-----------------创建一个新的Excel文件 workbook2工作薄,并将workbook的内容复制到workbook2中---------------------




                HSSFWorkbook workbook2 = new HSSFWorkbook();//创建一个workbook2工作薄,其实就是我们常说的Excel文件    

                ISheet sheet2 = workbook2.CreateSheet("Sheet1");//为workbook2工作创建一个Sheet1页   



                //根据sheet页的总行数,来创建sheet2页的总行数  
                for (int i = 0; i <= cellRows; i++)
                {
                    row = sheet.GetRow(i);
                    if (row == null)  //如果数据源的当前行为null ,就结束本次循环,开始下次循环
                    {
                        continue;
                    }
                    else
                    {
                        sheet2.CreateRow(i); //否则就 创建workbook2中sheet2页的第i行
                    }

                    //根据shee1页的总列数,创建shee2页的总列数  
                    for (int j = 0; j < maxCellCount; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell != null)  //如果数据源的当前格不为null
                        {
                            if (cell.CellType == CellType.String) //cell.CellType是获取数据源当前格的数据类型,如果它的数据类型为String类型
                            {
                                string sourceCellValue = sheet.GetRow(i).GetCell(j).StringCellValue; //获取数据源当前格的值

                                //将这个值赋给workbook2中sheet2页的第i行,第j列
                                sheet2.GetRow(i).CreateCell(j, CellType.String).SetCellValue(sourceCellValue);
                            }

                            if (cell.CellType == CellType.Numeric) //如果数据源的当前格的类型为Numeric类型
                            {
                                double sourceCellValue = sheet.GetRow(i).GetCell(j).NumericCellValue;
                                sheet2.GetRow(i).CreateCell(j, CellType.Numeric).SetCellValue(sourceCellValue);
                            }

                        }



                    }

                }

                //开打指定路径下的文件,如果文件不存在则创建文件,并打开,以进行写入
                using (Stream stream = File.OpenWrite("d:/excel2.xls"))
                {
                    workbook2.Write(stream);  //将这个workbook2文件写入到stream流中    
                }

                context.Response.Write("OK");  //提示OK
            }


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using System.IO;
using System.Text;


namespace 导入导出Excel
{
    /// <summary>
    /// Excel导入导出 的摘要说明
    /// </summary>
    public class Excel导入导出 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "application/x-excel";
            string name = HttpUtility.UrlEncode("Excel文件.xls"); //给要下载的文件命名为Excel文件.xls

            context.Response.AddHeader("Content-disposition", "attachment; filename="+name);//添加以下载文件的形式打开文件的报文头
           

            //------------------------------------------创建Excel,并将数据写入--------  



            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个Excel文件    

            ISheet sheet = workbook.CreateSheet("Sheet1");//创建一个页   

            IRow row = sheet.CreateRow(0); //创建sheet页的第0行(索引从0开始)    

          
            row.CreateCell(0, CellType.String).SetCellValue("C罩杯");//创建第0格
            row.CreateCell(1, CellType.String).SetCellValue("D罩杯");//创建第二格并为赋值
            row.CreateCell(2, CellType.String).SetCellValue("A罩杯");//创建第三格并为赋值
            row.CreateCell(3, CellType.String).SetCellValue("F罩杯");//创建第四格并为赋值
            row.CreateCell(18, CellType.Numeric).SetCellValue(5);//创建第17格并为赋值

            //得到一个excel.xls文件的文件流 【开打指定路径下的文件,如果文件不存在则创建文件,并打开,以进行写入】    
            using (Stream stream = File.OpenWrite("d:/excel.xls"))
            {

                workbook.Write(stream); //将这个workbook文件写入到stream流中
            }






            //------------------------------------------读取Excel的数据-------------  


            using (Stream stream1 = File.OpenRead("d:/excel.xls"))
            {

                //读取workbook这个工作薄的第0个Sheet(GetSheetAt(0)),第0行(GetRow(0)),第0格(GetCell(0))的值                 
                //string s = workbook.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue;  

                int cellRows = sheet.LastRowNum;

                //获取workbook中sheet页的最后一行的行号【行号从0开始】
                int sheetRowCount = sheet.LastRowNum;

                //这个循环是获取shee1页中"所有的行中"具有"最多列"的"列数"
                int maxCellCount = 0;
                for (int i = sheet.FirstRowNum; i <= cellRows; i++) //遍历sheet页的所有的行
                {
                    row = sheet.GetRow(i); //获取当前行
                    if (row == null) 这一句很关键,因为没有数据的行默认是null 
                    {
                        continue; //既然当前行无数据那就结束本次循环,进行下次循环
                    }
                    else
                    {
                        int cellCount = row.LastCellNum;  //获取当前行的列数
                        if (cellCount > maxCellCount)    //如果当前行的列数大于"最大列数maxCellCount",那么我就将当前行的列数设置为最大的列数
                        {
                            maxCellCount = cellCount;  //for循环结束后,maxCellCount就得到了"所有的行中"具有"最多列"的"列数"
                        }
                    }
                }






                //-----------------创建一个新的Excel文件 workbook2工作薄,并将workbook的内容复制到workbook2中---------------------




                HSSFWorkbook workbook2 = new HSSFWorkbook();//创建一个workbook2工作薄,其实就是我们常说的Excel文件    

                ISheet sheet2 = workbook2.CreateSheet("Sheet1");//为workbook2工作创建一个Sheet1页   



                //根据sheet页的总行数,来创建sheet2页的总行数  
                for (int i = 0; i <= cellRows; i++)
                {
                    row = sheet.GetRow(i);
                    if (row == null)  //如果数据源的当前行为null ,就结束本次循环,开始下次循环
                    {
                        continue;
                    }
                    else
                    {
                        sheet2.CreateRow(i); //否则就 创建workbook2中sheet2页的第i行
                    }

                    //根据shee1页的总列数,创建shee2页的总列数  
                    for (int j = 0; j < maxCellCount; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell != null)  //如果数据源的当前格不为null
                        {
                            if (cell.CellType == CellType.String) //cell.CellType是获取数据源当前格的数据类型,如果它的数据类型为String类型
                            {
                                string sourceCellValue = sheet.GetRow(i).GetCell(j).StringCellValue; //获取数据源当前格的值

                                //将这个值赋给workbook2中sheet2页的第i行,第j列
                                sheet2.GetRow(i).CreateCell(j, CellType.String).SetCellValue(sourceCellValue);
                            }

                            if (cell.CellType == CellType.Numeric) //如果数据源的当前格的类型为Numeric类型
                            {
                                double sourceCellValue = sheet.GetRow(i).GetCell(j).NumericCellValue;
                                sheet2.GetRow(i).CreateCell(j, CellType.Numeric).SetCellValue(sourceCellValue);
                            }

                        }



                    }

                }

                workbook2.Write(context.Response.OutputStream); //将文件写入到一个context的输出流中,在用户的浏览器中显示出来,注意,我在开头添加了一个context.Response.AddHeader("Content-disposition", "attachment; filename="+name);报文头。意思是让它以下载文件的形式打开



                //开打指定路径下的文件,如果文件不存在则创建文件,并打开,以进行写入
                //using (Stream stream = File.OpenWrite("d:/excel2.xls"))
                //{
                //    workbook2.Write(stream);  //将这个workbook2文件写入到stream流中    
                //}

                context.Response.Write("OK");  //提示OK
            }


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


NPOI是一个基于.NET平台的开源库,用于操作Office文档,包括读取、删除、修改和写入Excel数据。下面是使用NPOI进行Excel数据操作的一些示例代码: 读取Excel数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; // 打开Excel文件 using (var file = new FileStream("path/to/excel.xlsx", FileMode.Open, FileAccess.Read)) { // 创建工作簿 var workbook = new XSSFWorkbook(file); // 获取第一个工作表 var sheet = workbook.GetSheetAt(0); // 遍历行和列 for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++) { var row = sheet.GetRow(rowIndex); if (row == null) continue; for (int colIndex = 0; colIndex < row.LastCellNum; colIndex++) { var cell = row.GetCell(colIndex); if (cell == null) continue; // 处理单元格数据 .WriteLine(cell.ToString()); } } } ``` 删除Excel数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; // 打开Excel文件 using (var file = new FileStream("path/to/excel.xlsx", FileMode.Open, FileAccess.ReadWrite)) { // 创建工作簿 var workbook = new XSSFWorkbook(file); // 获取第一个工作表 var sheet = workbook.GetSheetAt(0); // 删除指定行 var rowIndexToDelete = 5; var rowToDelete = sheet.GetRow(rowIndexToDelete); if (rowToDelete != null) { sheet.RemoveRow(rowToDelete); } // 保存修改 workbook.Write(file); } ``` 修改Excel数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; // 打开Excel文件 using (var file = new FileStream("path/to/excel.xlsx", FileMode.Open, FileAccess.ReadWrite)) { // 创建工作簿 var workbook = new XSSFWorkbook(file); // 获取第一个工作表 var sheet = workbook.GetSheetAt(0); // 修改指定单元格的数据 var rowIndexToModify = 2; var colIndexToModify = 3; var rowToModify = sheet.GetRow(rowIndexToModify); if (rowToModify != null) { var cellToModify = rowToModify.GetCell(colIndexToModify); if (cellToModify != null) { cellToModify.SetCellValue("New Value"); } } // 保存修改 workbook.Write(file); } ``` 写入Excel数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; // 创建工作簿 var workbook = new XSSFWorkbook(); // 创建工作表 var sheet = workbook.CreateSheet("Sheet1"); // 创建行和单元格,并写入数据 for (int rowIndex = 0; rowIndex < 5; rowIndex++) { var row = sheet.CreateRow(rowIndex); for (int colIndex = 0; colIndex < 5; colIndex++) { var cell = row.CreateCell(colIndex); cell.SetCellValue($"Row {rowIndex + 1}, Col {colIndex + 1}"); } } // 保存Excel文件 using (var file = new FileStream("path/to/excel.xlsx", FileMode.Create, FileAccess.Write)) { workbook.Write(file); } ``` 以上是一些使用NPOI进行Excel数据操作的示例代码,你可以根据自己的需求进行相应的修改和扩展。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值