C#NPOI對Excel的操作、導入導出時異常處理、最全的NPOI資料在這裡~

来源:https://www.cnblogs.com/chenyanbin/archive/2019/05/10/10832614.html
-Advertisement-
Play Games

一、Excel理論知識 最新版NPOI2.4.1鏈接:https://pan.baidu.com/s/1iTgJi2hGsRQHyw2S_4dIUw 提取碼:adnq • 整個Excel表格叫做工作簿:WorkBook • 工作簿由以下幾部分組成 a.頁(Sheet); b.行(Row); c.單元 ...


一、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         }

五、資料庫中數據,導出Excel

 private void button4_Click(object sender, EventArgs e)
        {
            // 需引用命名空間
            // using System.Data.SqlClient;
            // using NPOI.HSSF.UserModel;
            // using NPOI.SS.UserModel;
            // using System.IO;
            //1、通過ado.net讀取數據
            string strSql = "SELECT * FROM Students";
            SqlDataReader reader = sqlHelper.ExecuteReader(strSql,CommandType.Text);
            if (reader.HasRows) //若有數據
            {
                //2、將讀取到的數據寫入到Excel中
                //2.1創建工作簿WorkBook對象
                IWorkbook wkBook = new HSSFWorkbook();
                //2.2創建工作表
                ISheet sheet = wkBook.CreateSheet("人員信息表"); //工作表名稱 
                int rIndex = 0;               
                while (reader.Read())
                {
                    //每讀取一條數據,就創建一行row
                    IRow currentRow = sheet.CreateRow(rIndex);
                    rIndex++;
                    int ID = reader.GetInt32(0);
                    string name = reader.GetString(1);
                    int age = reader.GetInt32(2);
                    //向行中創建單元格  
                    currentRow.CreateCell(0).SetCellValue(ID); //第一個參數:單元格索引;第二個參數:給單元格賦值
                    currentRow.CreateCell(1).SetCellValue(name);
                    currentRow.CreateCell(2).SetCellValue(age);  
                }
                //創建文件
                string fileName = "人員信息表";
                string saveFilePath = ""; //導出時文件的路徑
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls"; //預設文件擴展名
                saveDialog.Filter = "Excel文件|*.xls"; //文件名篩選字元串
                saveDialog.FileName = fileName; //導出文件名稱
                saveDialog.ShowDialog(); //顯示視窗
                saveFilePath = saveDialog.FileName; //文件路徑
                //將workBook對象寫入到磁碟上
                FileStream fsWrite = new FileStream(saveFilePath, FileMode.Create);
                wkBook.Write(fsWrite);
                MessageBox.Show("數據導出成功!", "提示");
                fsWrite.Close(); //關閉文件流
                wkBook.Close();  //關閉工作簿
                fsWrite.Dispose(); //釋放文件流
            }
            else
            {
                MessageBox.Show("沒有數據");
            }
           

            //reader.Close();
        }                 
 1         public static SqlDataReader ExecuteReader(string strSql, CommandType cmdType, params SqlParameter[] pms)
 2         {
 3             SqlDataReader sr = null;
 4             SqlConnection conn = new SqlConnection(conStr);
 5             SqlCommand cmd = new SqlCommand(strSql, conn);
 6             cmd.CommandType = cmdType;
 7             if (pms != null)
 8             {
 9                 cmd.Parameters.AddRange(pms);
10             }
11             try
12             {
13                 if (conn.State == ConnectionState.Closed)
14                 {
15                     conn.Open();
16                 }
17                 sr = cmd.ExecuteReader();
18                 return sr;
19             }
20             catch (Exception EX)
21             {
22                 MessageBox.Show(EX.Message.ToString());
23             }
24             finally
25             {
26                 cmd.Dispose();
27             }
28             return sr;
29         }
函數

 六、Excel數據導入資料庫

資料庫欄位

Excel數據(必須和資料庫欄位對上)

 1         Thread th;  //聲明公共變數
 2         private void button5_Click(object sender, EventArgs e)
 3         {
 4             //因為要遍歷Excel中的數據,我們這裡用線程執行
 5             // 需引入命名空間
 6             //using System.Threading;
 7             //using System.Data.SqlClient;
 8             //using NPOI.HSSF.UserModel;
 9             //using NPOI.SS.UserModel;
10             //using System.IO;
11             //創建文件
12             object filePath = ""; // 文件路徑
13             OpenFileDialog ofd = new OpenFileDialog(); //創建文件
14             ofd.Filter = "Excel文件|*.xls";
15             ofd.ShowDialog();
16             filePath = ofd.FileName;
17             th = new Thread(inportData);
18             th.IsBackground = true; //將線程設置為後臺進程
19             th.Start(filePath);
20             ofd.Dispose();
21         }
22         private void inportData(object filePath)
23         {
24             // 創建表副本 SELECT TOP 0 * INSERT INTO newTable FROM oldTable
25             //1、從Excel中讀取數據
26             if (filePath.ToString() != "")
27             {
28                 FileStream fsRead = new FileStream(filePath.ToString(), FileMode.Open);
29                 //一、創建工作簿
30                 IWorkbook workBook = new HSSFWorkbook(fsRead);
31                 string insert_sql = "";
32                 string insert_module = "INSERT INTO Student2 (id,name,age) VALUES ({0})";
33                 StringBuilder sb = new StringBuilder();
34                 for (int i = 0; i < workBook.NumberOfSheets; i++)
35                 {
36                     //獲取工作表
37                     ISheet sheet = workBook.GetSheetAt(i);
38                     for (int r = 0; r <= sheet.LastRowNum; r++) //遍歷當前工作表中的所有行
39                     {
40                         IRow currentRow = sheet.GetRow(r); //獲取每一行
41                         for (int c = 0; c < currentRow.LastCellNum; c++) //遍歷當前行中的所有列
42                         {
43                             //獲取每個單元格
44                             ICell cell = currentRow.GetCell(c);
45                             //listCells.Add(cell);
46                             sb.Append("'").Append(cell.ToString()).Append("',");
47                         }
48                         //拼接SQL語句
49                         insert_sql += string.Format(insert_module, sb.ToString().Substring(0, sb.ToString().Length - 1)) + ";";
50                         sb.Clear();
51                         //
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 當月第一天0時0分0秒DateTime.Now.AddDays(1 - DateTime.Now.Day).Date當月最後一天23時59分59秒DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1)取當... ...
  • 上一篇博客已經完成 C#ModBus Tcp Master的實現 本篇主要對不同的功能碼所發出的報文進行解析(包括請求報文及響應報文) 讀操作 功能碼 0x01 讀一組線圈 讀取站號為1 從地址12開始的10個線圈 測試結果 上一篇博客已經總結了讀操作報文格式,就按照格式劃分 報文解析: 註意:報文 ...
  • wpf 模擬抖音很火的羅盤時鐘,附源碼 前端時間突然發現,抖音火了個壁紙,就是黑底蕾絲~~~ 錯錯錯,黑底白字的羅盤時鐘! 作為程式員的我,也覺得很新穎,所以想空了研究下,這不,空下來了就用wpf,寫個屬於.net自己的羅盤時鐘,目前只實現了時分秒,農曆日期等邏輯都是一樣的,所以就略了,有興趣的朋友 ...
  • 簡介 主要是採用identity Server4 和ocelot 加上consul 實現簡單的客戶端模式 開發準備 環境準備 下載並安裝Consul具體請參考前幾篇的內容 項目介紹 創建ocelotServerTest項目 創建IdentityServer4Test項目 創建consulServer ...
  • 什麼是options請求 options請求為發送非簡單跨域請求前的預檢請求,若該請求未正常返回,瀏覽器會阻止後續的請求發送。 一般情況下,有三種方式會導致瀏覽器發起預檢請求 1.請求的方法不是GET/HEAD/POST 2.POST請求的Content Type並非application/x ww ...
  • .NET Core 常用第三方包 作者:高堂 原文地址:https://www.cnblogs.com/gaotang/p/10845370.html 寫在前面 最近在學習.NET Core 中經常用到的一些插件,在此做個整理備忘。 Autofac "Autofac" Alexinea.Autofa ...
  • Split是string中非常有趣的命令,它是用來分隔字元串中子字元串的字元數組,並且不包含分隔符的空數組或null,如下麵的代碼: String value = "This is a short string."; Char delimiter = ' '; String[] substrings ...
  • 業務場景:有主表、子表兩個GridView點擊主表的行,會自動讀取主表對應的子表數據但是如果反覆點擊會導致反覆讀取,其實反覆點擊的時候只需要最後一次執行查詢,前面的幾次點擊都是無意義操作根據這一需求設計了一個函數:private static List Tup = new List();/// //... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...