1. 程式人生 > >Npoi簡單讀寫Excel

Npoi簡單讀寫Excel

imp con tex play hive 分享 fin tails npoi

什麽是NPOI ?

  簡而言之,NPOI就是可以在沒有Office的情況下對Word或Excel文檔進行讀寫等操作。

使用方式 :

  1、準備NPOI的dll文件

    下載鏈接:https://npoi.codeplex.com/releases

  2、將下載的dll文件引入項目中

  3、引用命名空間

   技術分享圖片

須知:

  1、Excel表格分為:WorkBook(工作薄)-> Sheet(工作表) -> 行:Row 單元格:Cell。

  2、NPOI是POI的C#版本,NPOI的行和列的index都是從0開始

  3、POI讀取Excel有兩種格式一個是HSSF,另一個是XSSF。 HSSF和XSSF的區別如下:

    HSSF is the POI Project‘s pure Java implementation of the Excel ‘97(-2007) file format.
    XSSF is the POI Project‘s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
    即:HSSF適用2007以前的版本,XSSF適用2007版本及其以上的。

   下面使用NPOI讀取Excel例子:主要功能是將DataTable導入Excel,或將Excel讀取到DataTable中。

代碼如下:

 1       /// <summary>
 2         /// 將DataTable導入到Excel
 3         /// </summary>
 4         /// <param name="data">要導入的數據</param>
 5         /// <param name="filepath">導入的文件路徑(包含文件名稱)</param>
 6         /// <param name="sheename">要導入的表名</param>
 7         /// <param name="iscolumwrite">
是否寫入列名</param> 8 /// <returns>導入Excel的行數</returns> 9 public int DataTableToExcel(DataTable data, string filepath, string sheename, bool iscolumwrite) 10 { 11 int i = 0; 12 int j = 0; 13 int count = 0; 14 ISheet sheet = null; 15 using (fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 16 { 17 //根據Excel不同版本實例不同工作鋪 18 if (filepath.IndexOf(".xlsx") > 0) // 2007版本 19 { 20 workbook = new XSSFWorkbook(); 21 } 22 else if (filepath.IndexOf(".xls") > 0) // 2003版本 23 workbook = new HSSFWorkbook(); 24 25 try 26 { 27 if (workbook != null) 28 { 29 sheet = workbook.CreateSheet(sheename); 30 } 31 else 32 { 33 return -1; 34 } 35 36 if (iscolumwrite == true) //寫入DataTable的列名 37 { 38 IRow row = sheet.CreateRow(0); 39 for (j = 0; j < data.Columns.Count; ++j) 40 { 41 row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); 42 } 43 count = 1; 44 } 45 else 46 { 47 count = 0; 48 } 49 50 for (i = 0; i < data.Rows.Count; ++i) 51 { 52 IRow row = sheet.CreateRow(count); 53 for (j = 0; j < data.Columns.Count; ++j) 54 { 55 row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); 56 } 57 count++; 58 } 59 workbook.Write(fs); //寫入到excel 60 return count; 61 } 62 catch (Exception ex) 63 { 64 Console.WriteLine("Exception: " + ex.Message); 65 return -1; 66 } 67 finally { fs.Close(); fs.Dispose(); } 68 } 69 }

 1       /// <summary>
 2         /// 將Excel導入DataTable
 3         /// </summary>
 4         /// <param name="filepath">導入的文件路徑(包括文件名)</param>
 5         /// <param name="sheetname">工作表名稱</param>
 6         /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
 7         /// <returns>DataTable</returns>
 8         public DataTable ExcelToDataTable(string filepath, string sheetname, bool isFirstRowColumn)
 9         {
10             ISheet sheet = null;//工作表
11             DataTable data = new DataTable();
12 
13             var startrow = 0;
14             using (fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
15             {
16                 try
17                 {
18                     if (filepath.IndexOf(".xlsx") > 0) // 2007版本
19                         workbook = new XSSFWorkbook(fs);
20                     else if (filepath.IndexOf(".xls") > 0) // 2003版本
21                         workbook = new HSSFWorkbook(fs);
22                     if (sheetname != null)
23                     {
24                         sheet = workbook.GetSheet(sheetname);
25                         if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
26                         {
27                             sheet = workbook.GetSheetAt(0);
28                         }
29                     }
30                     else
31                     {
32                         sheet = workbook.GetSheetAt(0);
33                     }
34                     if (sheet != null)
35                     {
36                         IRow firstrow = sheet.GetRow(0);
37                         int cellCount = firstrow.LastCellNum; //行最後一個cell的編號 即總的列數
38                         if (isFirstRowColumn)
39                         {
40                             for (int i = firstrow.FirstCellNum; i < cellCount; i++)
41                             {
42                                 ICell cell = firstrow.GetCell(i);
43                                 if (cell != null)
44                                 {
45                                     string cellvalue = cell.StringCellValue;
46                                     if (cellvalue != null)
47                                     {
48                                         DataColumn column = new DataColumn(cellvalue);
49                                         data.Columns.Add(column);
50                                     }
51                                 }
52                             }
53                             startrow = sheet.FirstRowNum + 1;
54                         }
55                         else
56                         {
57                             startrow = sheet.FirstRowNum;
58                         }
59                         //讀數據行
60                         int rowcount = sheet.LastRowNum;
61                         for (int i = startrow; i < rowcount; i++)
62                         {
63                             IRow row = sheet.GetRow(i);
64                             if (row == null)
65                             {
66                                 continue; //沒有數據的行默認是null
67                             }
68                             DataRow datarow = data.NewRow();//具有相同架構的行
69                             for (int j = row.FirstCellNum; j < cellCount; j++)
70                             {
71                                 if (row.GetCell(j) != null)
72                                 {
73                                     datarow[j] = row.GetCell(j).ToString();
74                                 }
75                             }
76                             data.Rows.Add(datarow);
77                         }
78                     }
79                     return data;
80                 }
81                 catch (Exception ex)
82                 {
83                     Console.WriteLine("Exception: " + ex.Message);
84                     return null;
85                 }
86                 finally { fs.Close(); fs.Dispose(); }
87             }
88         }

測試代碼:

技術分享圖片
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 
 7 using NPOIHelperTool;
 8 using Bll;
 9 namespace ConsoleApplication1
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             DataTable data = new DataTable();
16             for (int i = 0; i < 5; ++i)
17             {
18                 data.Columns.Add("Columns_" + i.ToString(), typeof(string));
19             }
20 
21             for (int i = 0; i < 10; ++i)
22             {
23                 DataRow row = data.NewRow();
24                 row["Columns_0"] = "item0_" + i.ToString();
25                 row["Columns_1"] = "item1_" + i.ToString();
26                 row["Columns_2"] = "item2_" + i.ToString();
27                 row["Columns_3"] = "item3_" + i.ToString();
28                 row["Columns_4"] = "item4_" + i.ToString();
29                 data.Rows.Add(row);
30             }
31 
32             ExcelHelper h = new ExcelHelper();
33             DataTable de = h.ExcelToDataTable(@"E:\Myuser.xls", "Sheet1", true);
34             int c = h.DataTableToExcel(data, @"E:\Test.xls", "sheet1", true);
35             IList<student> a = TypeUtil.ToList<student>(de);
36         }
37 
38     }
39     class student
40     {
41         public string Id { get; set; }
42         public string Name { get; set; }
43         public string nc { get; set; }
44     }
45 }
View Code

參考:

https://www.cnblogs.com/Raning/p/5872822.html

https://blog.csdn.net/dcrmg/article/details/52356236

http://www.cnblogs.com/Erik_Xu/archive/2012/06/08/2541957.html

作者:遙遠的Ta

出處:https://www.cnblogs.com/lycb

Npoi簡單讀寫Excel