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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值