zoukankan      html  css  js  c++  java
  • C#进阶——NPOI

    NPOI:https://blog.csdn.net/mouday/article/details/81049219
    读取数据:https://www.cnblogs.com/chunxiong/p/9406178.html
    数据表格:https://www.cnblogs.com/Julyra/p/11506118.html

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
                //創建工作本 workbook和表sheet
                HSSFWorkbook wk = new HSSFWorkbook();
    
                //第一個創建的表的名字叫做例子
                //這個是什麼語法啊?為什麼接口可以直接等於createsheet啊,是因為是接口的另外一種實現形式嗎?
                ISheet sheet = wk.CreateSheet("例子");
    
                //創建行和單元格
                //創建行
                IRow row = sheet.CreateRow(2);
                //在第一行的第一列創建單元格
                ICell cell = row.CreateCell(0);
                //給相應的單元格賦值
                cell.SetCellValue("測試2");
    
                //打開一個xls文件,如果沒有則自行創建,如果存在則在創建時不要打開該文件
                //这次保存会把文档的所有数据都清除,然后保存自己的数据
                using (FileStream fs = File.OpenWrite(@"C:UsersleolamDesktop	est.xlsx"))
                {
                    wk.Write(fs);
                }
                
                //这里也可以采用下面这种方式
                //FileStreamfile =new FileStream(@"test.xls", FileMode.Create);
                //hssfworkbook.Write(file);
                //file.Close();
    
            }
        }
    }
    

    在原有基础上添加数据

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string tempPath = @"C:UsersleolamDesktop	est.xlsx";
                HSSFWorkbook wk = null;
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using(FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
                //获取创建文件的第一个表
                ISheet sheet = wk.GetSheetAt(0);
                //声明第一行
                IRow row = sheet.CreateRow(0);
    
                ICell cell = row.CreateCell(0);
    
                cell.SetCellValue("测试二");
    
                using(FileStream fs = File.OpenWrite(@"C:UsersleolamDesktop	est.xlsx"))
                {
                    wk.Write(fs);
                }
            }
        }
    }
    

    设置单元格样式

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string tempPath = @"C:UsersleolamDesktop	est.xlsx";
                HSSFWorkbook wk = null;
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using(FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
    
                //获取创建文件的第一个表
                ISheet sheet = wk.GetSheetAt(0);
    
                //声明第一行
                IRow row = sheet.CreateRow(0);
    
                ICell cell = row.CreateCell(0);
    
                cell.SetCellValue("测试三");
    
                //设置边框格式
                ICellStyle cellStyle = wk.CreateCellStyle();
    
                //设置单元格上下左右边框线
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
    
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
    
                //设置完结构之后就是直接把样式保存到对应的单元格上
                cell.CellStyle = cellStyle;
    
    
                using (FileStream fs = File.OpenWrite(@"C:UsersleolamDesktop	est.xlsx"))
                {
                    wk.Write(fs);
                }
    
    
            }
        }
    }
    

    复制表格数据到另一张表

    #region 正式导出无bug
        public HSSFWorkbook DataTableToExcelOK(DataTable dt, DataTable dt1, DataTable dt2, string filePath, string tpath, bool isColumnName)
        {
            //创建一个空的行变量
            IRow row = null;
    
            //创建一个空的表变量
            ISheet sheet = null;
    
            //创建一个空的单元格
            ICell cell = null;
    
            //声明起始单元格
            int startRow = 0;
    
            //声明一个空的excel文件变量
            IWorkbook workbook = null;
    
            //fileinfo是文件操作类,用来操作文件
            FileInfo ff = new FileInfo(tpath);
            //声明一个空的流变量
            FileStream fs2 = null;
            //如果问价已经存在就删除
            if (ff.Exists)
            {
                ff.Delete();
            }
            
            //打开模板
            FileStream fileRead = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileRead);
            //打开新创建的
            FileStream fileSave2 = new FileStream(tpath, FileMode.Open, FileAccess.Read);//打开新创建的excel
            HSSFWorkbook book2 = new HSSFWorkbook(fileSave2);
    
            HSSFSheet CPS = hssfworkbook.GetSheetAt(6) as HSSFSheet;//获取模板的sheet
            
            CPS.CopyTo(book2, "报价体系V1.5", true, true);//将模板复制到新建的excel中
    
            using (FileStream fileSave = new FileStream(tpath, FileMode.Open, FileAccess.Write))
            {
                book2.Write(fileSave);
                fileSave.Close();
    
                #region 将数据导入excel中
                using (fs2 = File.OpenRead(tpath))
                {
                    // 2007版本  
                    if (tpath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs2);
                    // 2003版本  
                    else if (tpath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs2);
    
    
                    if (workbook != null)
                    {
                        sheet = workbook.GetSheetAt(0);
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数 
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(3);//表头行  
                                int cellCount = firstRow.LastCellNum;//表头列数  
                                if (isColumnName)
                                {
                                    startRow = 3;//如果第一行是列名,则从第二行开始读取
                                    if (dt != null && dt.Rows.Count > 0)
                                    {
    
                                        sheet.GetRow(1).GetCell(1).SetCellValue(dt1.Rows[0][0].ToString());//dt1需要填充的表头数据
                                        sheet.GetRow(1).GetCell(4).SetCellValue(dt1.Rows[0][0].ToString());
                                        sheet.GetRow(1).GetCell(7).SetCellValue(dt1.Rows[0][1].ToString());
    
                                        int rowtbCount = Convert.ToInt32(dt.Rows.Count + 3);//datatable行数 dt内容数据 
                                        int columnCount = dt.Columns.Count;//列数  
    
                                        for (int i = startRow; i < rowtbCount; i++)
                                        {
                                            // row = sheet.CreateRow(i+1);
                                            row = sheet.CopyRow(i, i + 1);
                                            for (int j = 0; j < columnCount; j++)
                                            {
                                                cell = row.GetCell(j + 2);//excel第二行开始写入数据  
                                                if (j == 7)
                                                {
                                                    cell.SetCellValue(dt.Rows[i - 3][j].ToDouble());//dt.Rows[i - 3][j].ToDouble()
                                                }
                                                else
                                                {
                                                    cell.SetCellValue(dt.Rows[i - 3][j].ToString());
                                                }
                                            }
    
                                        }
    
                                        sheet.GetRow(rowtbCount + 2).GetCell(9).SetCellValue(dt2.Rows[0][3].ToString());
                                        sheet.GetRow(rowtbCount + 2).GetCell(16).SetCellValue(dt2.Rows[0][0].ToString());
                                        sheet.GetRow(rowtbCount + 2).GetCell(18).SetCellValue(dt2.Rows[0][1].ToString());
                                        sheet.GetRow(rowtbCount + 2).GetCell(22).SetCellValue(dt2.Rows[0][2].ToString());//dt2表尾数据
    
                                        using (fs2 = File.OpenWrite(tpath))
                                        {
                                            workbook.Write(fs2);//向打开的这个xls文件中写入数据  
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion
    
                return workbook as HSSFWorkbook;
            }
        }
        #endregion
    

    获取数据行数,不包括夹在数据之间额空白行

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    using System;
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string tempPath = @"C:UsersleolamDesktop	est.xls";
                
                //声明excel文件控件
                HSSFWorkbook wk = null;
    
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using (FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
    
                ISheet sheet = wk.GetSheetAt(0);
                
                //获取有数据的行数,如果某一行没有数据,则整行都不算。
                Console.WriteLine(sheet.LastRowNum);
                //另外一种判断方式,结果都相同
                Console.WriteLine(sheet.PhysicalNumberOfRows);
    
            }
        }
    }
    

    判断所有行数,如果空白行夹在中间,也正常计入

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    using System;
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string tempPath = @"C:UsersleolamDesktop	est.xls";
                
                //声明excel文件控件
                HSSFWorkbook wk = null;
    
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using (FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
    
                ISheet sheet = wk.GetSheetAt(0);
    
                int count = 0;
                int realCount = sheet.LastRowNum;
                while (sheet.GetRow(count) != null || count < realCount)
                {
                    count++;
                }
                Console.WriteLine(count);
    
            }
        }
    }
    

    统计excel表行数和列数,最终输出结果

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    using System;
    namespace Lean.Leo.NPOI2
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.OutputEncoding = System.Text.Encoding.Unicode;
    
                string tempPath = @"C:UsersleolamDesktop	est.xls";
                
                //声明excel文件控件
                HSSFWorkbook wk = null;
    
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using (FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
    
                ISheet sheet = wk.GetSheetAt(0);
    
                int count = 0;
                int realCount = sheet.LastRowNum;
                //判断有多少行,
                while (sheet.GetRow(count) != null || count < realCount)
                {
                    if (sheet.GetRow(count) != null)
                    {
                        Console.WriteLine("这行有" + sheet.GetRow(count).LastCellNum + "列");
                    }
                    else
                    {
                        Console.WriteLine("第" + count + "行为空行");
                    }
                    count++;
                }
                Console.WriteLine("总行数为:"+count);
            }
        }
    }
    

    复制excel文件表到另一个excel表中

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO;
    using System;
    namespace Lean.Leo.NPOI2e
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.OutputEncoding = System.Text.Encoding.Unicode;
    
                string tempPath = @"C:UsersleolamDesktop	est.xls";
                
                //声明excel文件控件
                HSSFWorkbook wk = null;
    
                //tempPath:表示保存地址,FileMode:表示电脑如何操作文件,fileaccess:表示对文件内容进行什么操作,
                using (FileStream fs = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    //把xls文件读入workbook变量里,之后就可以关闭了
                    wk = new HSSFWorkbook(fs);
                    fs.Close();
                }
    
                //读取表
                ISheet sheet = wk.GetSheetAt(0);
    
    
                //统计行数,不包括夹在中间的空行
                int count = 0;
                //统计行数,包括夹在中间的空行
                int realCount = sheet.LastRowNum;
    
                //创建目标表
                HSSFWorkbook wk2 = new HSSFWorkbook();
    
                ISheet targetSheet = wk2.CreateSheet("复制表");
    
                IRow row = null;
    
                IRow targetRow = null;
    
                ICell targetCell = null;
    
                //通过while循环实现对每一个单元格的遍历和访问
                while (sheet.GetRow(count) != null || count < realCount)
                {
                    //通过
                    if (sheet.GetRow(count) != null)
                    {
                        //注意,每一次重新创建,就会把之前同一行的数据清除
                        targetRow = targetSheet.CreateRow(count);
    
                        for (int i = 0; i < sheet.GetRow(count).LastCellNum; i++)
                        {
                            //数据源表的行变量
                             row = sheet.GetRow(count);
    
                            //这里通过设置为var,可以进行null判断
                            var cell = row.GetCell(i);
    
                            //如果单元格数值为空,则跳过复制过程
                            if(cell == null)
                            {
                                continue;
                            }
                            
    
                            targetCell = targetRow.CreateCell(i);
    
                            targetCell.SetCellValue(cell.ToString());
    
                            Console.WriteLine(targetCell.ToString());
                            
                        }
    
                        Console.WriteLine("这行有" + sheet.GetRow(count).LastCellNum + "列");
    
                    }
                    else
                    {
                        Console.WriteLine("第" + count + "行为空行");
                    }
                    count++;
                }
                using (FileStream fs = File.OpenWrite(@"C:UsersleolamDesktop	est2.xls"))
                {
                    wk2.Write(fs);
                }
                    Console.WriteLine("总行数为:" + count);
            }
        }
    }
    
  • 相关阅读:
    学电脑入门与提高
    Autodesk Revit Architecture 2014官方标准教程
    Photoshop移动UI界面设计实用教程 全彩超值版
    中文版SQL Server 2000开发与管理应用实例
    Excel2016数据处理与分析从新手到高手
    云计算(第三版)
    无线局域网搭建与管理
    R语言数据挖掘
    Spring 3.0就这么简单
    SVN使用教程总结
  • 原文地址:https://www.cnblogs.com/LY-CS/p/13259695.html
Copyright © 2011-2022 走看看