C# NPOI 작업 Excel

3345 단어 Excel

using System;
using System.Collections;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel; 

        // 
        public static void importExcel(string fileName)
        {
            FileStream file = null;
            try
            {
                file = new FileStream(fileName, FileMode.Open);
                using (file)
                {
                    using (IWorkbook workbook = new HSSFWorkbook(file))
                    {
                        using (ISheet sheet = workbook.GetSheetAt(0))// 
                        {

                            IRow headerRow = sheet.GetRow(0);// 
                            int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                            int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1


                            for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                            {
                                IRow row = sheet.GetRow(i);

                                if (row != null)
                                {
                                    for (int j = row.FirstCellNum; j < cellCount; j++)
                                    {
                                        if (row.GetCell(j) != null)
                                            Console.WriteLine(row.GetCell(j));
                                    }
                                }

                            }
                        }
                    }
                }

            }
            finally
            {
                if (file != null)
                    file.Close();
            }
        }

         // 
        public static void exportExcel(string fileName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            FileStream file = new FileStream(fileName, FileMode.Create);
            try
            {
                ISheet sheet =  workbook.CreateSheet("A");
                workbook.CreateSheet("B");
                workbook.CreateSheet("D");
                IRow dataRow = sheet.CreateRow(0);
                dataRow.CreateCell(0).SetCellValue("haha");
                dataRow = sheet.CreateRow(1);
                dataRow.CreateCell(0).SetCellValue("hoho");

                //   if (File.Exists(fileName)) File.Delete(fileName);
                
                workbook.Write(ms);
                ms.WriteTo(file);
                ms.Flush();
                
            }finally
            {
                ms.Close();
                file.Close();
            }
        }

좋은 웹페이지 즐겨찾기