1. 程式人生 > >使用NPOI讀寫Excel例項

使用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(); } } }