使用NPOI读取Excel到DataTable

一、NPOI介绍:

使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作

二、安装NPOI

新建控制台应用程序>管理NuGet程序包>搜索NPOI>安装NPOI


三.下面是我需要的读取的Excel文件,数据格式如下:


四.添加ExcelHelper类:

[csharp]  view plain  copy
  1. using System;  
  2. using NPOI.SS.UserModel;  
  3. using NPOI.XSSF.UserModel;  
  4. using NPOI.HSSF.UserModel;  
  5. using System.IO;  
  6. using System.Data;  
  7.   
  8. namespace NPOI.ReadExcel  
  9. {  
  10.     public class ExcelHelper : IDisposable  
  11.     {  
  12.         private string fileName = null//文件名  
  13.         private IWorkbook workbook = null;  
  14.         private FileStream fs = null;  
  15.         private bool disposed;  
  16.   
  17.         public ExcelHelper(string fileName)  
  18.         {  
  19.             this.fileName = fileName;  
  20.             disposed = false;  
  21.         }  
  22.   
  23.         /// <summary>  
  24.         /// 将DataTable数据导入到excel中  
  25.         /// </summary>  
  26.         /// <param name="data">要导入的数据</param>  
  27.         /// <param name="isColumnWritten">DataTable的列名是否要导入</param>  
  28.         /// <param name="sheetName">要导入的excel的sheet的名称</param>  
  29.         /// <returns>导入数据行数(包含列名那一行)</returns>  
  30.         public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)  
  31.         {  
  32.             int i = 0;  
  33.             int j = 0;  
  34.             int count = 0;  
  35.             ISheet sheet = null;  
  36.   
  37.             fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);  
  38.             if (fileName.IndexOf(".xlsx") > 0) // 2007版本  
  39.                 workbook = new XSSFWorkbook();  
  40.             else if (fileName.IndexOf(".xls") > 0) // 2003版本  
  41.                 workbook = new HSSFWorkbook();  
  42.   
  43.             try  
  44.             {  
  45.                 if (workbook != null)  
  46.                 {  
  47.                     sheet = workbook.CreateSheet(sheetName);  
  48.                 }  
  49.                 else  
  50.                 {  
  51.                     return -1;  
  52.                 }  
  53.   
  54.                 if (isColumnWritten == true//写入DataTable的列名  
  55.                 {  
  56.                     IRow row = sheet.CreateRow(0);  
  57.                     for (j = 0; j < data.Columns.Count; ++j)  
  58.                     {  
  59.                         row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);  
  60.                     }  
  61.                     count = 1;  
  62.                 }  
  63.                 else  
  64.                 {  
  65.                     count = 0;  
  66.                 }  
  67.   
  68.                 for (i = 0; i < data.Rows.Count; ++i)  
  69.                 {  
  70.                     IRow row = sheet.CreateRow(count);  
  71.                     for (j = 0; j < data.Columns.Count; ++j)  
  72.                     {  
  73.                         row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());  
  74.                     }  
  75.                     ++count;  
  76.                 }  
  77.                 workbook.Write(fs); //写入到excel  
  78.                 return count;  
  79.             }  
  80.             catch (Exception ex)  
  81.             {  
  82.                 Console.WriteLine("Exception: " + ex.Message);  
  83.                 return -1;  
  84.             }  
  85.         }  
  86.   
  87.         /// <summary>  
  88.         /// 将excel中的数据导入到DataTable中  
  89.         /// </summary>  
  90.         /// <param name="sheetName">excel工作薄sheet的名称</param>  
  91.         /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>  
  92.         /// <returns>返回的DataTable</returns>  
  93.         public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)  
  94.         {  
  95.             ISheet sheet = null;  
  96.             DataTable data = new DataTable();  
  97.             int startRow = 0;  
  98.             try  
  99.             {  
  100.                 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);  
  101.                 if (fileName.IndexOf(".xlsx") > 0) // 2007版本  
  102.                     workbook = new XSSFWorkbook(fs);  
  103.                 else if (fileName.IndexOf(".xls") > 0) // 2003版本  
  104.                     workbook = new HSSFWorkbook(fs);  
  105.   
  106.                 if (sheetName != null)  
  107.                 {  
  108.                     sheet = workbook.GetSheet(sheetName);  
  109.                     if (sheet == null//如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet  
  110.                     {  
  111.                         sheet = workbook.GetSheetAt(0);  
  112.                     }  
  113.                 }  
  114.                 else  
  115.                 {  
  116.                     sheet = workbook.GetSheetAt(0);  
  117.                 }  
  118.                 if (sheet != null)  
  119.                 {  
  120.                     IRow firstRow = sheet.GetRow(0);  
  121.                     int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数  
  122.   
  123.                     if (isFirstRowColumn)  
  124.                     {  
  125.                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i)  
  126.                         {  
  127.                             ICell cell = firstRow.GetCell(i);  
  128.                             if (cell != null)  
  129.                             {  
  130.                                 string cellValue = cell.StringCellValue;  
  131.                                 if (cellValue != null)  
  132.                                 {  
  133.                                     DataColumn column = new DataColumn(cellValue);  
  134.                                     data.Columns.Add(column);  
  135.                                 }  
  136.                             }  
  137.                         }  
  138.                         startRow = sheet.FirstRowNum + 1;  
  139.                     }  
  140.                     else  
  141.                     {  
  142.                         startRow = sheet.FirstRowNum;  
  143.                     }  
  144.   
  145.                     //最后一列的标号  
  146.                     int rowCount = sheet.LastRowNum;  
  147.                     for (int i = startRow; i <= rowCount; ++i)  
  148.                     {  
  149.                         IRow row = sheet.GetRow(i);  
  150.                         if (row == nullcontinue//没有数据的行默认是null         
  151.   
  152.                         DataRow dataRow = data.NewRow();  
  153.                         for (int j = row.FirstCellNum; j < cellCount; ++j)  
  154.                         {  
  155.                             if (row.GetCell(j) != null//同理,没有数据的单元格都默认是null  
  156.                                 dataRow[j] = row.GetCell(j).ToString();  
  157.                         }  
  158.                         data.Rows.Add(dataRow);  
  159.                     }  
  160.                 }  
  161.   
  162.                 return data;  
  163.             }  
  164.             catch (Exception ex)  
  165.             {  
  166.                 Console.WriteLine("Exception: " + ex.Message);  
  167.                 return null;  
  168.             }  
  169.         }  
  170.   
  171.         public void Dispose()  
  172.         {  
  173.             Dispose(true);  
  174.             GC.SuppressFinalize(this);  
  175.         }  
  176.   
  177.         protected virtual void Dispose(bool disposing)  
  178.         {  
  179.             if (!this.disposed)  
  180.             {  
  181.                 if (disposing)  
  182.                 {  
  183.                     if (fs != null)  
  184.                         fs.Close();  
  185.                 }  
  186.   
  187.                 fs = null;  
  188.                 disposed = true;  
  189.             }  
  190.         }  
  191.     }  
  192. }  
五,读取文件到DataTable:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace NPOI.ReadExcel  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             ExcelHelper excel_helper = new ExcelHelper(AppDomain.CurrentDomain.BaseDirectory + "test.xlsx");  
  15.             DataTable dt = excel_helper.ExcelToDataTable("",true);  
  16.   
  17.             List<string> tableList=GetColumnsByDataTable(dt);  
  18.             for (int i = 0; i < tableList.Count; i++)  
  19.             {  
  20.                 foreach (DataRow item in dt.Rows)  
  21.                 {  
  22.                     try  
  23.                     {  
  24.                         if (item[0].ToString() != "")  
  25.                         {  
  26.                             if (i < tableList.Count - 1 & item[i + 1].ToString()!="")  
  27.                             {  
  28.                                 Console.WriteLine(item[0].ToString()+"\t"+item[i+1].ToString());  
  29.                             }  
  30.                         }  
  31.                     }  
  32.                     catch (Exception ex)  
  33.                     { }  
  34.                 }  
  35.                 Console.WriteLine("");  
  36.             }  
  37.   
  38.             Console.ReadKey();  
  39.         }  
  40.   
  41.         /// <summary>  
  42.         /// 根据datatable获得列名  
  43.         /// </summary>  
  44.         /// <param name="dt">表对象</param>  
  45.         /// <returns>返回结果的数据列数组</returns>  
  46.         public static List<string> GetColumnsByDataTable(DataTable dt)  
  47.         {  
  48.             List<string> strColumns =new List<string> ();  
  49.   
  50.             if (dt.Columns.Count > 0)  
  51.             {  
  52.                 int columnNum = 0;  
  53.                 columnNum = dt.Columns.Count;;  
  54.                 for (int i = 0; i < dt.Columns.Count; i++)  
  55.                 {  
  56.                     strColumns.Add(dt.Columns[i].ColumnName);  
  57.                 }  
  58.             }  
  59.             return strColumns;  
  60.         }   
  61.     }  
  62. }  



版权声明:可自由转载、引用,请署名作者注明文章出处! https://blog.csdn.net/heyangyi_19940703/article/details/52292755
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值