C# NPOI操作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();
}
}

你可能感兴趣的:(C#)