NPOI 操作Excel

 

NPOI官网

 

NPOI教程

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
namespace NPOI读取
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Stream fs = new FileStream("Files/收支记录.xls", FileMode.Open))
            {
                IWorkbook workbook = new HSSFWorkbook(fs);
                for (int i = 0; i < workbook.NumberOfSheets; i++)
                {
                    ISheet sheet = workbook.GetSheetAt(i);
                    //Console.WriteLine(sheet.SheetName);
                    if (sheet.LastRowNum > 0)
                    {
                        for (int j = 0; j < sheet.LastRowNum; j++)
                        {
                            IRow row = sheet.GetRow(j);
                            for (int k = 0; k < row.LastCellNum; k++)
                            {
                                ICell cell = row.GetCell(k);
                                Console.Write(cell.ToString() + "   ");

                            }
                            Console.WriteLine("");
                        }
                        Console.WriteLine("-----------------------------------");
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

  

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
namespace NPOI写入数据
{
    class Program
    {
        static void Main(string[] args)
        {
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("九九乘法表");
            for (int i = 1; i <=9; i++)
            {
                IRow row = sheet.CreateRow(i-1);
                for (int j = 1; j <= 9-(9-i); j++)
                {
                    ICell cell = row.CreateCell(j-1,CellType.String);
                    cell.SetCellValue(j+"*"+i+"="+(i*j));
                }
            }
            using (Stream fs = new FileStream(@"C:\Users\yokin\Desktop\my.xls", FileMode.OpenOrCreate))
            {
                workbook.Write(fs);
            }
            Console.WriteLine("OK");
            Console.ReadKey();
        }
    }
}

  

 

posted @ 2015-05-18 22:47  linyongqin  阅读(202)  评论(0编辑  收藏  举报