Excel的读取和写入

一、Excel理论知识

最新版NPOI2.4.1链接:https://pan.baidu.com/s/1iTgJi2hGsRQHyw2S_4dIUw  提取码:adnq 

• 整个Excel表格叫做工作簿:WorkBook

• 工作簿由以下几部分组成

  a.页(Sheet);

  b.行(Row);

  c.单元格(Cell);

二、处理Excel的技术

•OLE Automation:程序启动一个Excel进程,然后和Excel进程进行通讯来运行Excel的操作。

  优点:强大,Excel能实现的功能,都可以实现

  缺点:必须装Excel

•把Excel当成数据库,使用Microsoft.Jet.OleDb访问Excel,只适合二维结构,功能少,不用装Excel

•OpenXML,微软提供的读写Excel的技术,只能处理xlsx格式文件

•NPOI、MyXls,能够分析Excel文件的格式,能够进行常用Excel操作,不依赖于Excel,节省资源,没有安全性和性能的问题。只能处理xls格式文件、不能处理xlsx这样的新版本Excel文件格式。处理xlsx用OpenXML

1 描述工作簿的类:IWorkbook(接口)、HSSFWorkbook(具体实现类)
2 
3 描述工作表的类:ISheet(接口)、HSSFSheet(具体实现类)

三、NPOI导出

方式一(默认导出位置)

 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             List<Person> list = new List<Person>() {
 4                 new Person(){Name="张三",Age="15",Email="[email protected]" },
 5                 new Person(){Name="李四",Age="16",Email="[email protected]" },
 6                 new Person(){Name="王五",Age="17",Email="[email protected]" }
 7             };
 8             // 引用命名空间
 9             // using NPOI.HSSF.UserModel;
10             // using NPOI.SS.UserModel;
11             // using System.IO;
12             //将List集合中的内容导出到Excel中
13             //1、创建工作簿对象
14             IWorkbook wkBook = new HSSFWorkbook();
15             //2、在该工作簿中创建工作表对象
16             ISheet sheet = wkBook.CreateSheet("人员信息"); //Excel工作表的名称
17             //2.1向工作表中插入行与单元格
18             for (int i = 0; i < list.Count; i++)
19             {
20                 //在Sheet中插入创建一行
21                 IRow row = sheet.CreateRow(i);
22                 //在该行中创建单元格
23                 //方式一
24                 //ICell cell = row.CreateCell(0);
25                 //cell.SetCellValue(list[i].Name);
26                 //方式二
27                 row.CreateCell(0).SetCellValue(list[i].Name); //给单元格设置值:第一个参数(第几个单元格);第二个参数(给当前单元格赋值)
28                 row.CreateCell(1).SetCellValue(list[i].Age);
29                 row.CreateCell(2).SetCellValue(list[i].Email);
30             }
31             //3、写入,把内存中的workBook对象写入到磁盘上
32             FileStream fsWrite = File.OpenWrite("Person.xls");  //导出时Excel的文件名
33             wkBook.Write(fsWrite);
34             MessageBox.Show("写入成功!", "提示");
35             fsWrite.Close(); //关闭文件流
36             wkBook.Close();  //关闭工作簿
37             fsWrite.Dispose(); //释放文件流
38 39         }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _01NPOI的写入
 8 {
 9     public class Person
10     {
11         public string Name { get; set; }
12         public string Age { get; set; }
13         public string Email { get; set; }
14     }
15 }
Person类

方式二(更友好的一种方式,用户可以指定导出位置)推荐

 1         private void button3_Click(object sender, EventArgs e)
 2         {
 3             List<Person> list = new List<Person>() {
 4                 new Person(){Name="张三",Age="15",Email="[email protected]" },
 5                 new Person(){Name="李四",Age="16",Email="[email protected]" },
 6                 new Person(){Name="王五",Age="17",Email="[email protected]" }
 7             };
 8             //创建文件
 9             string fileName = "人员信息表";
10             string saveFilePath = ""; //导出时文件的路径
11             SaveFileDialog saveDialog = new SaveFileDialog();
12             saveDialog.DefaultExt = "xls"; //默认文件扩展名
13             saveDialog.Filter = "Excel文件|*.xls"; //文件名筛选字符串
14             saveDialog.FileName = fileName; //导出文件名称
15             saveDialog.ShowDialog(); //显示窗口
16             saveFilePath = saveDialog.FileName; //文件路径
17             // 引用命名空间
18             // using NPOI.HSSF.UserModel;
19             // using NPOI.SS.UserModel;
20             // using System.IO;
21             //将List集合中的内容导出到Excel中
22             //1、创建工作簿对象
23             IWorkbook wkBook = new HSSFWorkbook();
24             //2、在该工作簿中创建工作表对象
25             ISheet sheet = wkBook.CreateSheet("人员信息"); //Excel工作表的名称
26             //2.1向工作表中插入行与单元格
27             for (int i = 0; i < list.Count; i++)
28             {
29                 //在Sheet中插入创建一行
30                 IRow row = sheet.CreateRow(i);
31                 //在该行中创建单元格
32                 //方式一
33                 //ICell cell = row.CreateCell(0);
34                 //cell.SetCellValue(list[i].Name);
35                 //方式二
36                 row.CreateCell(0).SetCellValue(list[i].Name); //给单元格设置值:第一个参数(第几个单元格);第二个参数(给当前单元格赋值)
37                 row.CreateCell(1).SetCellValue(list[i].Age);
38                 row.CreateCell(2).SetCellValue(list[i].Email);
39             }
40             //3、写入,把内存中的workBook对象写入到磁盘上
41             FileStream fsWrite = new FileStream(saveFilePath,FileMode.Create);
42             wkBook.Write(fsWrite);
43             MessageBox.Show("写入成功!", "提示");
44             fsWrite.Close(); //关闭文件流
45             wkBook.Close();  //关闭工作簿
46             fsWrite.Dispose(); //释放文件流
47         }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _01NPOI的写入
 8 {
 9     public class Person
10     {
11         public string Name { get; set; }
12         public string Age { get; set; }
13         public string Email { get; set; }
14     }
15 }
Person类

方式三、导出dataGridView数据

 1         public static void ExportExcel(string fileName, DataGridView dgv)
 2         {
 3             string saveFileName = "";
 4             SaveFileDialog saveDialog = new SaveFileDialog();
 5             saveDialog.DefaultExt = "xls";
 6             saveDialog.Filter = "Excel文件|*.xls";
 7             saveDialog.FileName = fileName;
 8             saveDialog.ShowDialog();
 9             saveFileName = saveDialog.FileName;
10 
11             HSSFWorkbook workbook = new HSSFWorkbook();
12             MemoryStream ms = new MemoryStream();
13 
14             NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
15 
16             int rowCount = dgv.Rows.Count+1;
17             int colCount = dgv.Columns.Count;
18             int r1;
19             NPOI.SS.UserModel.IRow dataRow1 = sheet.CreateRow(0);
20 
21             for (int i = 0; i < rowCount; i++)
22             {
23                 NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(i);
24                 for (int j = 1; j < colCount; j++)
25                 {
26                     if (i == 0)
27                     {
28                         r1 = i;
29                     }
30                     else
31                     {
32                         r1 = i - 1;
33                     }
34                     if (dgv.Columns[j].Visible && dgv.Rows[r1].Cells[j].Value != null)
35                     {
36                         NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(j-1);
37                         if (i == 0)
38                         {
39                             cell.SetCellValue(dgv.Columns[j].HeaderCell.Value.ToString());
40                             continue;
41                         }
42                         cell.SetCellValue(dgv.Rows[r1].Cells[j].FormattedValue.ToString());
43                     }
44                     else
45                     {
46                         NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(j-1);
47                         cell.SetCellValue("");
48                     }
49                 }
50             }
51 
52             workbook.Write(ms);
53             FileStream file = new FileStream(saveFileName, FileMode.Create);
54             workbook.Write(file);
55             file.Close();
56             workbook = null;
57             ms.Close();
58             ms.Dispose();
59         }
DGV中数据导出Excel

 四、NPOI读取Excel内容

 1         private void button2_Click(object sender, EventArgs e)
 2         {
 3             //需要读取的文件:人员表.xls
 4             // 创建文件
 5             OpenFileDialog ofd = new OpenFileDialog();
 6             ofd.Filter = "Excel文件|*.xls";
 7             ofd.ShowDialog();
 8             string filePath = ofd.FileName;
 9             FileStream fsRead=null;
10             IWorkbook wkBook = null;
11             if (filePath != "")
12             {
13                 //1、创建一个工作簿workBook对象
14                 fsRead = new FileStream(filePath, FileMode.Open);
15                 //将人员表.xls中的内容读取到fsRead中
16                 wkBook = new HSSFWorkbook(fsRead);
17                 //2、遍历wkBook中的每个工作表Sheet
18                 for (int i = 0; i < wkBook.NumberOfSheets; i++)
19                 {
20                     //获取每个工作表对象
21                     ISheet sheet = wkBook.GetSheetAt(i);
22                     //获取每个工作表的行
23                     //foreach遍历 sheet.GetEnumerator
24                     for (int r = 0; r < sheet.LastRowNum; r++)
25                     {
26                         //获取工作表中的每一行
27                         IRow currentRow = sheet.GetRow(r);
28                         //遍历当前行中的每个单元格
29                         for (int c = 0; c < currentRow.LastCellNum; c++)
30                         {
31                             try
32                             {
33                                 //获取每个单元格
34                                 ICell cell = currentRow.GetCell(c);
35                                 if (cell == null) //如果单元格为空时,程序会报错,这里判断提示用户,用try catch防止程序蹦
36                                 {
37                                     MessageBox.Show(string.Format("第{0}行,第{1}列单元格为空!",r,c));
38                                 }
39                                 CellType cType = cell.CellType; // 获取单元格中的类型
40                                 MessageBox.Show(cType.ToString());
41                                 //判断当前单元格的数据类型,可以拓展
42                                 switch (cType)
43                                 {
44                                     case CellType.Numeric: //数字
45                                         MessageBox.Show("我是数字");
46                                         break;
47                                     case CellType.String: //字符串
48                                         MessageBox.Show("我是字符串");
49                                         break;
50                                     case CellType.Boolean:
51                                         MessageBox.Show("我是布尔值");
52                                         break;    
53                                 }
54                                 //获取单元格的值
55                                 //日期
56                                 DateTime date = cell.DateCellValue;
57                                 //数字
58                                 double num = cell.NumericCellValue;
59                                 //字符串
60                                 string str = cell.StringCellValue;
61                                 //布尔值
62                                 bool bl = cell.BooleanCellValue;
63                             }
64                             catch (Exception EX)
65                             {
66 
67                             }
68                           
69                         }
70                     }
71                 }            
72             }
73             else
74             {
75                 MessageBox.Show("选择文件失败!","提示");
76             }
77             fsRead.Close();
78             wkBook.Close();
79             fsRead.Dispose();
80 
81         }

项目链接:https://pan.baidu.com/s/1kQ2IycR8WoJ8LZkmjLA_mA  提取码:4ks9 

有不懂的同学,欢迎下方留言~~~

猜你喜欢

转载自www.cnblogs.com/chenyanbin/p/10832614.html