使用NPOI读写Excel实例

特别注意:如果使用FileStream 打开文件之后没有Close,有几率导致Excel损坏,使用using方式可以避免

using System;
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; //如果读取xls引用NPOI.HSSF.UserModel
namespace ParseExcel
{
    class Program
    {
        private static string PATH = @"D:/testin.xlsx";
        private static void Main(string[] args)
        {
            using (FileStream fs = new FileStream(PATH, FileMode.Open, FileAccess.ReadWrite))
            {
                IWorkbook wk = new XSSFWorkbook(fs);
                int sheetCount = wk.NumberOfSheets;
                for (int i = 0; i < sheetCount; i++)
                {
                    ISheet sheet = wk.GetSheetAt(0);
                    for (int j = 0; j <= sheet.LastRowNum; j++)
                    {
                        IRow row = sheet.GetRow(j);
                        if (row == null) continue;
                        if (row.FirstCellNum == row.LastCellNum) continue;
                        List<string> list = new List<string>();
                        for (int z = 0; z < row.LastCellNum; z++)
                        {
                            Console.Write(row.GetCell(z).ToString());
                        }
                    }
                }
                using (Stream st = new FileStream(@"D:/testout.xlsx", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    wk.Write(st);
                }
                wk.Close();
            }
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(经验)