.Net中Excel使用NPOI读取
2020-07-08 本文已影响0人
小船翻不翻
就是源码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
namespace 对excel表的读写
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//创建读取文件流
using (FileStream fs = File.Open(@"d:\2.xls", FileMode.Open))
{
//创建一个工作簿
using (Workbook wk = new HSSFWorkbook(fs))
{
//遍历每个工作表
for (int i = 0; i < wk.NumberOfSheets; i++)
{
//根据索引获取每个工作表
using (Sheet sh = wk.GetSheetAt(i))
{
//输出每个表名
Console.WriteLine("============{0}=============", sh.SheetName);
//遍历每行
for (int j = 0; j <= sh.LastRowNum; j++)
{
Row cr = sh.GetRow(j);
//遍历每行中的列
for (int k = 0; k < cr.LastCellNum; k++)
{
//Console.Write(cr.GetCell(k).ToString() + "\t");
tt.AppendText(cr.GetCell(k).ToString() + "\t");
}
tt.AppendText("/n");
Console.WriteLine();
}
}
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (Workbook wk=new HSSFWorkbook())
{
using (Sheet sh=wk.CreateSheet("转转转"))
{
for (int i = 0; i < 3; i++)
{
Row rw = sh.CreateRow(i);
Cell ce = rw.CreateCell(0);
ce.SetCellValue("姓名" + i);
Cell ce1 = rw.CreateCell(1);
ce1.SetCellValue("性别" + i);
Cell ce2 = rw.CreateCell(2);
ce2.SetCellValue("年龄" + i);
}
using (FileStream fs = File.OpenWrite(@"d:\2.xls"))
{
wk.Write(fs);
}
}
}
MessageBox.Show("写入成功!");
}
}
}