NPOI 2.2.0.0,初级读取导入Excel
1.读取Excel,将数据绑定到dgv上
private void button1_Click(object sender, EventArgs e)
{
List<Book> books = new List<Book>();
//1.读取Excel文件
using (FileStream fsReder = File.OpenRead("练习.xlsx"))
{
//2.创建工作簿
IWorkbook wk = new XSSFWorkbook("练习.xlsx");
//IWorkbook wk=new XSSFWorkbook(fsReder);
//获取第一个工作表
ISheet sheet = wk.GetSheetAt();
//3.遍历每一行,行和列的索引都是从0开始
for (int i = ; i < sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
//MessageBox.Show(row.GetCell(0).ToString());
//4.读取每一行的数据,加到对象中
books.Add(new Book()
{
Name = row.GetCell().ToString(),
One = row.GetCell().ToString(),
Two = row.GetCell().ToString(),
Three = row.GetCell().ToString(),
Four = row.GetCell().ToString(),
Five = row.GetCell().ToString(),
Six = row.GetCell().ToString(), });
}
}
//5.绑定数据
dgv.DataSource = books;
dgv.AutoGenerateColumns = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
MessageBox.Show("操作完成");
}
2.将数据导入到Excel中
private void button2_Click(object sender, EventArgs e)
{
List<Book> books = new List<Book>()
{
new Book() {Name = "火影忍者",One ="",Two = "",Three = "",Four = "",Five = "",Six = ""},
new Book() {Name = "海贼王", One ="",Two = "",Three = "",Four = "",Five = "",Six = ""},
new Book() {Name = "死神",One ="",Two = "",Three = "",Four = "",Five = "",Six = ""},
new Book() {Name = "游戏王",One ="",Two = "",Three = "",Four = "",Five = "",Six = ""},
};
//1.创建工作簿
using (FileStream fsWrite = File.OpenWrite("1.xlsx"))
{
IWorkbook wk = new XSSFWorkbook();
//2.创建第一个工作表
ISheet sheet = wk.CreateSheet("第一张表");
//第一行设置标题
IRow rowHead = sheet.CreateRow(); rowHead.CreateCell().SetCellValue("图书名");
rowHead.CreateCell().SetCellValue("一月");
rowHead.CreateCell().SetCellValue("二月");
rowHead.CreateCell().SetCellValue("三月");
rowHead.CreateCell().SetCellValue("四月");
rowHead.CreateCell().SetCellValue("五月");
rowHead.CreateCell().SetCellValue("六月"); //3.在工作表的最后一行下,循环创建工作表的每一行,添加数据
for (int i = ; i < books.Count; i++)
{
IRow row = sheet.CreateRow(i);
row.CreateCell().SetCellValue(books[i].Name);
row.CreateCell().SetCellValue(books[i].One);
row.CreateCell().SetCellValue(books[i].Two);
row.CreateCell().SetCellValue(books[i].Three);
row.CreateCell().SetCellValue(books[i].Four);
row.CreateCell().SetCellValue(books[i].Five);
row.CreateCell().SetCellValue(books[i].Six);
}
wk.Write(fsWrite);
} MessageBox.Show("操作完成");
}