C#使用NPOI将DataGridView内数据写入电子表格Excel

C#使用NPOI将DataGridView内数据写入电子表格Excel
NPOI能够在用户没有安装office的情况下读写office文件,包括.xls/.doc/.ppt等类型的文件。本文介绍的是使用NPOI库内的函数读写Excel(.xls)内的内容。在使用NPOI之前首先先要将NPOI添加到工程应用中,NPOI的官网链接:https://archive.codeplex.com/?p=npoi,本文最后也附带了代码和文件。

一、将DataGridView控件内的数据写入Excel文件,如果Excel文件不存在则新建表格,如果文件存在则新建并替换该表格。

写如Excel前需要知道的:

引入命名空间;
创建文件流;
创建workbook;
创建sheet;
创建行row;
创建单元格cell;
修改单元格的值;
1.引入命名空间:

本文操作所用到的NPOI中命名空间有:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

2.创建文件流:

使用FileStream创建文件流FileStream fs = new FileStream(文件路径, 文件操作方式, 文件读写权限);

FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

3.创建workbook:

创建workbook只要创建一个HSSFWorkbook实例就可以了,HSSFWorkbook是NPOI.HSSF.UserModel中的类。NPOI.HSSF.UserModel.HSSFWorkbook这个类便是用来创建.xls文件的。

HSSFWorkbook workbook = new HSSFWorkbook();

4.创建sheet:

创建完workbook后,还需要为其添加工作表,即创建sheet。创建sheet同样是创建ISheet实例便可以了,ISheet是NPOI.SS.UserModel中用来创建工作表的类。

ISheet sheet = workbook.CreateSheet("Sheet1");

5.创建行row:

创建行的方法与上述类似,即创建IRow实例。

IRow row = sheet.CreateRow(i);//i为行序号

6.创建单元格cell:

同样的创建单元格就是创建ICell实例。

ICell cell = row.CreateCell(j);//j为列序号

7.修改单元格值:

修改单元格值通过调用cell的方法SetCellValue()即可;

放个例子:

复制代码

 1 //------------【函数:将表格控件保存至Excel文件(新建/替换)】------------    
 2 
 3         //filePath要保存的目标Excel文件路径名
 4         //datagGridView要保存至Excel的表格控件
 5         //------------------------------------------------------------------------
 6         public static bool SaveToExcelNew(string filePath,DataGridView dataGridView)
 7         {
 8             bool result = true;
 9 
10             FileStream fs = null;//创建一个新的文件流
11             HSSFWorkbook workbook = null;//创建一个新的Excel文件
12             ISheet sheet = null;//为Excel创建一张工作表
13 
14             //定义行数、列数、与当前Excel已有行数
15             int rowCount = dataGridView.RowCount;//记录表格中的行数
16             int colCount = dataGridView.ColumnCount;//记录表格中的列数
17 
18             //为了防止出错,这里应该判定一下文件与文件是否存在
19                         
20             //创建工作表
21             try
22             {
23                 fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
24                 workbook = new HSSFWorkbook();
25                 sheet = workbook.CreateSheet("Sheet1");
26                 IRow row = sheet.CreateRow(0);
27                 for (int j = 0; j < colCount; j++)  //列循环
28                 {
29                     if (dataGridView.Columns[j].Visible && dataGridView.Rows[0].Cells[j].Value != null)
30                     {
31                         ICell cell = row.CreateCell(j);//创建列
32                         cell.SetCellValue(dataGridView.Columns[j].HeaderText.ToString());//更改单元格值                  
33                     }
34                 }
35             }
36             catch
37             {
38                 result = false;
39                 return result;
40             }
41 
42             for (int i = 0; i < rowCount; i++)      //行循环
43             {
44                 //防止行数超过Excel限制
45                 if (i >= 65536)
46                 {
47                     result = false;
48                     break;
49                 }
50                 IRow row = sheet.CreateRow(1 + i);  //创建行
51                 for (int j = 0; j < colCount; j++)  //列循环
52                 {
53                     if (dataGridView.Columns[j].Visible && dataGridView.Rows[i].Cells[j].Value != null)
54                     {
55                         ICell cell = row.CreateCell(j);//创建列
56                         cell.SetCellValue(dataGridView.Rows[i].Cells[j].Value.ToString());//更改单元格值                  
57                     }
58                 }
59             }
60             try
61             {
62                 workbook.Write(fs);
63             }
64             catch
65             {
66                 result = false;
67                 return result;
68             }
69             finally
70             {
71                 if (fs != null)
72                 {
73                     fs.Close();
74                     fs.Dispose();
75                 }
76                 workbook = null;
77             }
78             return result;
79         }
复制代码
 

二、将DataGridView控件内的数据写入Excel文件,如果Excel文件不存在则新建表格,如果文件存在则将数据添加至表格末尾。

思路与上文例子相同,只是在写入电子表格时使用ISheet的LastRowNum属性获取Excel的最后一行,将新的数据一次向下存放。

放个例子:

复制代码
  1         //------------【函数:将表格控件保存至Excel文件(添加/新建)】------------    
  2         //filePath要保存的目标Excel文件路径名
  3         //datagGridView要保存至Excel的表格控件
  4         //------------------------------------------------
  5         public static bool SaveToExcelAdd(string filePath, DataGridView dataGridView)
  6         {
  7             bool result = true;
  8 
  9             FileStream fs = null;//创建一个新的文件流
 10             HSSFWorkbook workbook = null;//创建一个新的Excel文件
 11             ISheet sheet = null;//为Excel创建一张工作表
 12 
 13             //定义行数、列数、与当前Excel已有行数
 14             int rowCount = dataGridView.RowCount;//记录表格中的行数
 15             int colCount = dataGridView.ColumnCount;//记录表格中的列数
 16             int numCount = 0;//Excell最后一行序号
 17 
 18             //为了防止出错这里应该判断文件夹是否存在
 19             
 20             //判断文件是否存在
 21             if (!File.Exists(filePath))
 22             {
 23                 try
 24                 {
 25                     fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
 26                     workbook = new HSSFWorkbook();
 27                     sheet = workbook.CreateSheet("Sheet1");
 28                     IRow row = sheet.CreateRow(0);
 29                     for (int j = 0; j < colCount; j++)  //列循环
 30                     {
 31                         if (dataGridView.Columns[j].Visible && dataGridView.Rows[0].Cells[j].Value != null)
 32                         {
 33                             ICell cell = row.CreateCell(j);//创建列
 34                             cell.SetCellValue(dataGridView.Columns[j].HeaderText.ToString());//更改单元格值                  
 35                         }
 36                     }
 37                     workbook.Write(fs);
 38                 }
 39                 catch
 40                 {
 41                     result = false;
 42                     return result;
 43                 }
 44                 finally
 45                 {
 46                     if (fs != null)
 47                     {
 48                         fs.Close();
 49                         fs.Dispose();
 50                         fs = null;
 51                     }
 52                     workbook = null;
 53                 }
 54             }
 55             //创建指向文件的工作表
 56             try
 57             {
 58                 fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
 59                 workbook = new HSSFWorkbook(fs);//.xls
 60                 sheet = workbook.GetSheetAt(0);
 61                 if (sheet == null)
 62                 {
 63                     result = false;
 64                     return result;
 65                 }
 66                 numCount = sheet.LastRowNum + 1;
 67             }
 68             catch
 69             {
 70                 result = false;
 71                 return result;
 72             }
 73 
 74             for (int i = 0; i < rowCount; i++)      //行循环
 75             {
 76                 //防止行数超过Excel限制
 77                 if (numCount + i >= 65536)
 78                 {
 79                     result = false;
 80                     break;
 81                 }
 82                 IRow row = sheet.CreateRow(numCount + i);  //创建行
 83                 for (int j = 0; j < colCount; j++)  //列循环
 84                 {
 85                     if (dataGridView.Columns[j].Visible && dataGridView.Rows[i].Cells[j].Value != null)
 86                     {
 87                         ICell cell = row.CreateCell(j);//创建列
 88                         cell.SetCellValue(dataGridView.Rows[i].Cells[j].Value.ToString());//更改单元格值                  
 89                     }
 90                 }
 91             }
 92             try
 93             {
 94                 fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
 95                 workbook.Write(fs);
 96             }
 97             catch
 98             {
 99                 result = false;
100                 return result;
101             }
102             finally
103             {
104                 if (fs != null)
105                 {
106                     fs.Close();
107                     fs.Dispose();
108                     fs = null;
109                 }
110                 workbook = null;
111             }
112             return result;
113         }

复制代码

本文所说的只是单纯的实现写入电子表格的功能,关于NPOI更加详细的说明可以参考NPOI手册,或者博客,这个给一个连接:http://blog.csdn.net/pan_junbiao/article/details/39717443

如何将Excel内数据读取到DataGridView中,参考下篇博文:http://blog.csdn.net/nicewe/article/details/79621698

本文的源文件程序(Visual Studio 2017)与NPOI.DLL文件下载地址:https://download.csdn.net/download/nicewe/10296960

发布了55 篇原创文章 · 获赞 4 · 访问量 1413

猜你喜欢

转载自blog.csdn.net/BowenXu11/article/details/104803126