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

1、Excel理論知識

最新版NPOI2.4.1連接:https://pan.baidu.com/s/1iTgJi2hGsRQHyw2S_4dIUw  提取碼:adnq c++

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

• 工做簿由如下幾部分組成

  a.頁(Sheet);sql

  b.行(Row);數據庫

  c.單元格(Cell);數組

2、處理Excel的技術

•OLE Automation:程序啓動一個Excel進程,而後和Excel進程進行通信來運行Excel的操做。

  優勢:強大,Excel能實現的功能,均可以實現安全

  缺點:必須裝Excelide

•把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(具體實現類)

3、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="123@qq.com" },
 5                 new Person(){Name="李四",Age="16",Email="456@qq.com" },
 6                 new Person(){Name="王五",Age="17",Email="789@qq.com" }
 7             };
 8             // 引用命名空間
 9             // using NPOI.HSSF.UserModel;
10             // using NPOI.SS.UserModel;
11             // using System.IO;
12             //將List集合中的內容導出到Excel中
13             //一、建立工做簿對象
14             IWorkbook wkBook = new HSSFWorkbook();
15             //二、在該工做簿中建立工做表對象
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             //三、寫入,把內存中的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="123@qq.com" },
 5                 new Person(){Name="李四",Age="16",Email="456@qq.com" },
 6                 new Person(){Name="王五",Age="17",Email="789@qq.com" }
 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             //一、建立工做簿對象
23             IWorkbook wkBook = new HSSFWorkbook();
24             //二、在該工做簿中建立工做表對象
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             //三、寫入,把內存中的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類

方式3、導出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

 4、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                 //一、建立一個工做簿workBook對象
14                 fsRead = new FileStream(filePath, FileMode.Open);
15                 //將人員表.xls中的內容讀取到fsRead中
16                 wkBook = new HSSFWorkbook(fsRead);
17                 //二、遍歷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         }

5、數據庫中數據,導出Excel

 private void button4_Click(object sender, EventArgs e)
        {
            // 需引用命名空間
            // using System.Data.SqlClient;
            // using NPOI.HSSF.UserModel;
            // using NPOI.SS.UserModel;
            // using System.IO;
            //一、經過ado.net讀取數據
            string strSql = "SELECT * FROM Students";
            SqlDataReader reader = sqlHelper.ExecuteReader(strSql,CommandType.Text);
            if (reader.HasRows) //如有數據
            {
                //二、將讀取到的數據寫入到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         }
函數

 6、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             //一、從Excel中讀取數據
26             if (filePath.ToString() != "")
27             {
28                 FileStream fsRead = new FileStream(filePath.ToString(), FileMode.Open);
29                 //1、建立工做簿
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                         //listCells.Clear();
52                     }
53                 }
54                 //二、把讀取到的數據插入到數據庫
55                 //執行SQL語句
56                 int ret = sqlHelper.ExecuteNonQuery(insert_sql, CommandType.Text);
57                 if (ret == 1)
58                 {
59                     MessageBox.Show("導入成功!");
60                 }
61                 else
62                 {
63                     MessageBox.Show("導入失敗!");
64                 }
65                 fsRead.Close();
66                 fsRead.Dispose();
67             }
68             else
69             {
70                 MessageBox.Show("文件打開失敗!");
71             }
72         }
 1         /// <summary>
 2         /// 執行SQL語句
 3         /// </summary>
 4         /// <param name="strSql">sql語句</param>
 5         /// <param name="cmdType">CommandType.Text表明執行的SQL語句、CommandType.StoreProcedure表明執行的是存儲過程</param>
 6         /// <param name="pms">可變參數數組</param>
 7         /// <returns></returns>
 8         public static int ExecuteNonQuery(string strSql, CommandType cmdType, params SqlParameter[] pms)
 9         {
10             SqlConnection conn = new SqlConnection(conStr);
11             SqlCommand cmd = new SqlCommand(strSql, conn);
12             cmd.CommandType = cmdType;
13             if (pms != null)
14             {
15                 cmd.Parameters.AddRange(pms);
16             }
17             conn.Open();
18             SqlTransaction trans = conn.BeginTransaction();
19             try
20             {
21                 cmd.Transaction = trans;
22                 int count = cmd.ExecuteNonQuery();
23                 if (count > 0)
24                 {
25                     trans.Commit(); //提交事務
26                     return 1;
27                 }
28                 else
29                 {
30                     trans.Rollback(); //回滾事務
31                     return -1;
32                 }
33             }
34             catch (Exception EX)
35             {
36                 trans.Rollback(); //回滾事務
37                 MessageBox.Show(EX.Message.ToString());
38                 return -1;
39             }
40             finally
41             {
42                 conn.Close();
43                 conn.Dispose();
44                 cmd.Dispose();
45             }
46         }
函數

導入成功!!!

 

 

 7、設置單元樣式

1 ICellStyle style = workbook.CreateCellStyle();//建立樣式對象
2                 IFont font = workbook.CreateFont(); //建立一個字體樣式對象
3                 font.FontName = "方正舒體"; //和excel裏面的字體對應
4                 font.Color = new HSSFColor.PINK().GetIndex();//顏色參考NPOI的顏色對照表(替換掉PINK())
5                 font.IsItalic = true; //斜體
6                 font.FontHeightInPoints = 16;//字體大小
7                 font.Boldweight = short.MaxValue;//字體加粗
8                 style.SetFont(font); //將字體樣式賦給樣式對象
9                 cell.CellStyle = style; //把樣式賦給單元格
字體
1 ICellStyle style=workbook.CreateCellStyle();
2  style.FillForegroundColor = 14;  //具體數字表明的顏色看NPOI顏色對照表
3  style.FillPattern = FillPatternType.SOLID_FOREGROUND;
單元格前景色
1   行高:row.Height = 30 * 20;    //行高爲30
2 
3   列寬:sheet.SetColumnWidth(3, 13 * 256)   //第4列的列寬爲13
單元格寬高
1     單元格合併後,樣式以左上角的單元格爲準
2 
3     //CellRangeAddress四個參數爲:起始行,結束行,起始列,結束列
4 
5   sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
合併單元格
1  style.Alignment = HorizontalAlignment.CENTER;
水平居中
1     不須要寫「=」號
2 
3   cell.CellFormula = "公式";
設置公式
1 //上下左右
2 
3 styleFont.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;    
4 styleFont.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;  
5 styleFont.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;  
6 styleFont.BorderRight = NPOI.SS.UserModel.BorderStyle.THICK;
邊框

-----------------------如下異常處理-----------------------

1、數據庫中數據類型不一樣、爲空時處理

數據庫數據字體

導出處理ui

 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             //一、經過ADO.NET讀取數據
 4             string strSql = "SELECT * FROM userInfo";
 5             SqlDataReader reader = sqlHelper.ExecuteReader(strSql,CommandType.Text);
 6             if (reader.HasRows)
 7             {
 8                 //------建立文件開始------
 9                 string filePath = ""; //要導出的文件路徑
10                 SaveFileDialog saveFile = new SaveFileDialog();
11                 saveFile.Filter = "Excel文件|*.xls";
12                 saveFile.DefaultExt = "xls";
13                 saveFile.FileName = "人員表";
14                 DialogResult dResult= saveFile.ShowDialog(); //獲取用戶點擊的按鈕 保存/取消
15                 filePath = saveFile.FileName; //獲取導出路徑
16                 //------建立文件結果------
17                 if (dResult == DialogResult.Cancel) //用戶點擊的按鈕
18                 {
19                     MessageBox.Show("取消導出!");
20                     return;
21                 }               
22                 //建立工做簿
23                 IWorkbook workBook = new HSSFWorkbook();
24                 //建立工做表
25                 ISheet sheet = workBook.CreateSheet("人員表"); // 設置工做表名稱
26                 #region 建立第一行,設置列名
27                 //------------------------------------------------------------
28                 //建立第一行,第一行表示列名
29                 //循環查詢出每一列                
30                 IRow rowHead = sheet.CreateRow(0);
31                 for (int col = 0; col < reader.FieldCount; col++)
32                 {
33                     rowHead.CreateCell(col).SetCellValue(reader.GetName(col)); //獲取當前列的名字:reader.GetName(col)
34                 }
35                 //------------------------------------------------------------
36                 #endregion
37                 int rIndex = 1; //爲何行的索引爲1呢,由於沒有列名
38                 while (reader.Read())
39                 {
40                     IRow currentRow = sheet.CreateRow(rIndex); //建立行
41                     int id = reader.GetInt32(0);
42                     string user_id = reader.GetString(1);
43                     string user_pwd = reader.GetString(2);
44                     string user_name = reader.GetString(3);
45                     DateTime? dTime = reader.IsDBNull(4) ? null : (DateTime?)reader.GetDateTime(4); //聲明時加"?":可空類型
46                     int? num = reader.IsDBNull(5) ? null : (int?)reader.GetInt32(5);
47                     currentRow.CreateCell(0).SetCellValue(id);
48                     currentRow.CreateCell(1).SetCellValue(user_id);
49                     currentRow.CreateCell(2).SetCellValue(user_pwd);
50                     currentRow.CreateCell(3).SetCellValue(user_name);
51                     //若嫌麻煩的童鞋,此處能夠用for循環獲取值,而後用switch分別判斷單元格的類型,爲了方便讓你們理解,這裏不用for循環遍歷
52                     //for (int i = 0; i < reader.FieldCount; i++)
53                     //{
54                     //    string ret = reader.GetDataTypeName(i); // 獲取讀取到列的數據類型
55                     //    switch (ret)
56                     //    {
57                     //        case "string":
58                     //            break;
59                     //        case "int":
60                     //            break;
61                     //    }
62                     //}
63                     if (dTime == null) 
64                     {
65                         //若果爲NULL值,向Excel寫入一個單元格,類型爲Blank
66                         currentRow.CreateCell(4).SetCellType(CellType.Blank);
67                     }
68                     else
69                     {
70                         currentRow.CreateCell(4).SetCellValue((DateTime)dTime);
71                     }
72                     if (num==null)
73                     {
74                         currentRow.CreateCell(5).SetCellType(CellType.Blank);
75                     }
76                     else
77                     {
78                         currentRow.CreateCell(5).SetCellValue((int)num);
79                     }                   
80                     rIndex++;
81                 }
82                 //寫入Excel
83                 FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate);
84                 workBook.Write(fsRead);
85                 MessageBox.Show("導出成功");
86             }
87             else
88             {
89                 MessageBox.Show("沒有數據");
90             }
91             //二、寫入Excel
92         }

2、數據庫列爲日期類型,導出時

注:經過NPOI導出DateTime類型時,若是不轉換爲string,則須要設置一下單元格的格式

處理方法:

 1 #region 建立單元格
 2                         ICell cellLockDate = currentRow.CreateCell(4);
 3                         //賦值
 4                         cellLockDate.SetCellValue((DateTime)dTime);
 5                         #endregion
 6                         #region 設置樣式
 7                         HSSFCellStyle cellstyle = (HSSFCellStyle)workBook.CreateCellStyle();
 8                         HSSFDataFormat format = (HSSFDataFormat)workBook.CreateDataFormat();
 9                         cellstyle.DataFormat = format.GetFormat("yyyy-mm-dd");
10                         //賦值給單元格
11                         cellLockDate.CellStyle = cellstyle;
12                         #endregion
處理導出時日期格式
 1 第一種:日期格式
 2 
 3             cell.setCellValue(new Date(2008,5,5));
 4             //set date format
 5             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
 6             HSSFDataFormat format= demoWorkBook.createDataFormat();
 7             cellStyle.setDataFormat(format.getFormat("yyyy年m月d日"));
 8             cell.setCellStyle(cellStyle);
 9 
10 第二種:保留兩位小數格式
11             cell.setCellValue(1.2);
12             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
13             cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
14             cell.setCellStyle(cellStyle);
15 
16 這裏與上面有所不一樣,用的是HSSFDataFormat.getBuiltinFormat()方法,之因此用這個,是由於0.00是Excel內嵌的格式,完整的Excel內嵌格式列表你們能夠看這個窗口中的自定義列表:
17 
18  HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); 
19     style7.DataFormat = format.GetFormat("#,##0.00");//千分位,保留兩位小數
20  這裏就不一一列出了
21 
22 第三種:貨幣格式
23 
24             cell.setCellValue(20000);
25             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
26             HSSFDataFormat format= demoWorkBook.createDataFormat();
27             cellStyle.setDataFormat(format.getFormat("¥#,##0"));
28             cell.setCellStyle(cellStyle);
29 
30 第四種:百分比格式
31 
32             cell.setCellValue(20);
33             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
34             cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
35             cell.setCellStyle(cellStyle);
36   此種狀況跟第二種同樣
37 
38 第五種:中文大寫格式
39 
40             cell.setCellValue(20000);
41             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
42             HSSFDataFormat format= demoWorkBook.createDataFormat();
43             cellStyle.setDataFormat(format.getFormat("[DbNum2][$-804]0"));
44             cell.setCellStyle(cellStyle);
45 
46 第六種:科學計數法格式
47 
48             cell.setCellValue(20000);
49             HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
50             cellStyle.setDataFormat( HSSFDataFormat.getBuiltinFormat("0.00E+00"));
51             cell.setCellStyle(cellStyle);
52 --------------------- 
53 做者:liangyaomu 
54 來源:CSDN 
55 原文:https://blog.csdn.net/liangyaomu/article/details/52871994 
56 版權聲明:本文爲博主原創文章,轉載請附上博文連接!
處理其餘狀況彙總

 

3、Excel導入數據庫處理

本示例沒有用線程,建議用線程操做

 1 private void button2_Click(object sender, EventArgs e)
 2         {
 3             String filePath = "";
 4             OpenFileDialog ofd = new OpenFileDialog();
 5             ofd.Filter = "Excel文件|*.xls";
 6             DialogResult ret = ofd.ShowDialog();
 7             if (DialogResult.OK == ret)
 8             {
 9                 filePath = ofd.FileName;
10                 FileStream fsRead = new FileStream(filePath,FileMode.Open);
11                 //建立工做簿
12                 IWorkbook workBook = new HSSFWorkbook(fsRead);
13                 string insert_module = "INSERT INTO Students VALUES ({0})";
14                 string insert_sql = "";
15                 StringBuilder sb = new StringBuilder();
16                 for (int w = 0; w < workBook.NumberOfSheets; w++)
17                 {
18                     //獲取工做簿中的每一個工做表
19                     ISheet sheet = workBook.GetSheetAt(w);
20                     //遍歷當前工做表中的行
21                     for (int r = 0; r <= sheet.LastRowNum; r++)
22                     {
23                         //獲取當前行
24                         IRow currentRow = sheet.GetRow(r);
25                         if (currentRow!=null) //表示該行有對象
26                         {
27                             //遍歷當前行中的單元格
28                             for (int c = 0; c < currentRow.LastCellNum; c++)
29                             {
30                                 ICell currentCell = currentRow.GetCell(c);
31                                 //判斷單元格是否爲空
32                                 if (currentCell == null || currentCell.CellType == CellType.Blank || currentCell.ToString().Trim()=="")
33                                 {
34                                     //表示空值,須要往數據庫中插入空值
35                                     sb.Append("'',");
36                                 }
37                                 else
38                                 {
39                                     CellType cType = currentCell.CellType;
40                                     #region 拼接SQL語句
41                                     switch (cType)
42                                     {
43                                         case CellType.Numeric:
44                                             if (DateUtil.IsCellDateFormatted(currentCell) == true) //單元格類型爲數字,而且爲日期類型
45                                             {
46                                                 sb.Append("'").Append(currentCell.DateCellValue).Append("',");
47                                             }
48                                             else //不是日期類型
49                                             {
50                                                 sb.Append("'").Append(currentCell.NumericCellValue).Append("',");
51                                             }
52                                             break;
53                                         case CellType.String:
54                                             sb.Append("'").Append(currentCell.StringCellValue).Append("',");
55                                             break;
56                                     }
57                                     #endregion                             
58                                 }
59                             } //currentRow.LastCellNum
60                             insert_sql += string.Format(insert_module, sb.ToString().Substring(0, sb.ToString().Length - 1))+";";
61                             sb.Clear();
62                         }
63                     } //sheet.LastRowNum
64                 }
65                 int res = sqlHelper.ExecuteNonQuery(insert_sql.Substring(0,insert_sql.Length-1),CommandType.Text);
66                 if (res == 1)
67                 {
68                     MessageBox.Show("導入成功");
69                 }
70                 else
71                 {
72                     MessageBox.Show("導入失敗");
73                 }
74             }
75             else
76             {
77                 MessageBox.Show("請選擇導入文件!");
78             }
79         }
 1 public static int ExecuteNonQuery(string strSql, CommandType cmdType, params SqlParameter[] pms)
 2         {
 3             SqlConnection conn = new SqlConnection(conStr);
 4             SqlCommand cmd = new SqlCommand(strSql, conn);
 5             cmd.CommandType = cmdType;
 6             if (pms != null)
 7             {
 8                 cmd.Parameters.AddRange(pms);
 9             }
10             conn.Open();
11             SqlTransaction trans = conn.BeginTransaction();
12             try
13             {
14                 cmd.Transaction = trans;
15                 int count = cmd.ExecuteNonQuery();
16                 if (count > 0)
17                 {
18                     trans.Commit(); //提交事務
19                     return 1;
20                 }
21                 else
22                 {
23                     trans.Rollback(); //回滾事務
24                     return -1;
25                 }
26             }
27             catch (Exception EX)
28             {
29                 trans.Rollback(); //回滾事務
30                 MessageBox.Show(EX.Message.ToString());
31                 return -1;
32             }
33             finally
34             {
35                 conn.Close();
36                 conn.Dispose();
37                 cmd.Dispose();
38             }
39         }
函數

 

項目連接:https://pan.baidu.com/s/150J59Z3XP2DroZDy9HYfFA 

提取碼:nkw1

有不懂的童鞋,歡迎下方留言~~~

相關文章
相關標籤/搜索