1. 程式人生 > >C#中NPOI操作excel之讀取和寫入excel數

C#中NPOI操作excel之讀取和寫入excel數

一、下載引用

下載需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。

二、excel轉datatable類

  1. using System;  
  2. using System.Data;  
  3. using System.IO;  
  4. using NPOI.SS.UserModel;  
  5. using NPOI.XSSF.UserModel;  
  6. using NPOI.HSSF.UserModel;  
  7. namespace NPOIOprateExcel  
  8. {  
  9.     publicclass ExcelUtility  
  10.     {  
  11.         /// <summary>
  12.         /// 將excel匯入到datatable
  13.         /// </summary>
  14.         /// <param name="filePath">excel路徑</param>
  15.         /// <param name="isColumnName">第一行是否是列名</param>
  16.         /// <returns>返回datatable</returns>
  17.         public
    static DataTable ExcelToDataTable(string filePath, bool isColumnName)  
  18.         {  
  19.             DataTable dataTable = null;  
  20.             FileStream fs = null;  
  21.             DataColumn column = null;  
  22.             DataRow dataRow = null;  
  23.             IWorkbook workbook = null;  
  24.             ISheet sheet = null
    ;  
  25.             IRow row = null;  
  26.             ICell cell = null;  
  27.             int startRow = 0;  
  28.             try
  29.             {  
  30.                 using (fs = File.OpenRead(filePath))  
  31.                 {  
  32.                     // 2007版本
  33.                     if (filePath.IndexOf(".xlsx") > 0)  
  34.                         workbook = new XSSFWorkbook(fs);  
  35.                     // 2003版本
  36.                     elseif (filePath.IndexOf(".xls") > 0)  
  37.                         workbook = new HSSFWorkbook(fs);  
  38.                     if (workbook != null)  
  39.                     {  
  40.                         sheet = workbook.GetSheetAt(0);//讀取第一個sheet,當然也可以迴圈讀取每個sheet
  41.                         dataTable = new DataTable();  
  42.                         if (sheet != null)  
  43.                         {  
  44.                             int rowCount = sheet.LastRowNum;//總行數
  45.                             if (rowCount > 0)  
  46.                             {  
  47.                                 IRow firstRow = sheet.GetRow(0);//第一行
  48.                                 int cellCount = firstRow.LastCellNum;//列數
  49.                                 //構建datatable的列
  50.                                 if (isColumnName)  
  51.                                 {  
  52.                                     startRow = 1;//如果第一行是列名,則從第二行開始讀取
  53.                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)  
  54.                                     {  
  55.                                         cell = firstRow.GetCell(i);  
  56.                                         if (cell != null)  
  57.                                         {  
  58.                                             if (cell.StringCellValue != null)  
  59.                                             {  
  60.                                                 column = new DataColumn(cell.StringCellValue);  
  61.                                                 dataTable.Columns.Add(column);  
  62.                                             }  
  63.                                         }  
  64.                                     }  
  65.                                 }  
  66.                                 else
  67.                                 {  
  68.                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)  
  69.                                     {  
  70.                                         column = new DataColumn("column" + (i + 1));  
  71.                                         dataTable.Columns.Add(column);  
  72.                                     }  
  73.                                 }  
  74.                                 //填充行
  75.                                 for (int i = startRow; i <= rowCount; ++i)  
  76.                                 {  
  77.                                     row = sheet.GetRow(i);  
  78.                                     if (row == nullcontinue;  
  79.                                     dataRow = dataTable.NewRow();  
  80.                                     for (int j = row.FirstCellNum; j < cellCount; ++j)  
  81.                                     {  
  82.                                         cell = row.GetCell(j);                                          
  83.                                         if (cell == null)  
  84.                                         {  
  85.                                             dataRow[j] = "";  
  86.                                         }  
  87.                                         else
  88.                                         {  
  89.                                             //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  90.                                             switch (cell.CellType)  
  91.                                             {  
  92.                                                 case CellType.Blank:  
  93.                                                     dataRow[j] = "";  
  94.                                                     break;  
  95.                                                 case CellType.Numeric:  
  96.                                                     short format = cell.CellStyle.DataFormat;  
  97.                                                     //對時間格式(2015.12.5、2015/12/5、2015-12-5等)的處理
  98.                                                     if (format == 14 || format == 31 || format == 57 || format == 58)  
  99.                                                         dataRow[j] = cell.DateCellValue;  
  100.                                                     else
  101.                                                         dataRow[j] = cell.NumericCellValue;  
  102.                                                     break;  
  103.                                                 case CellType.String:  
  104.                                                     dataRow[j] = cell.StringCellValue;  
  105.                                                     break;  
  106.                                             }  
  107.                                         }  
  108.                                     }  
  109.                                     dataTable.Rows.Add(dataRow);  
  110.                                 }  
  111.                             }  
  112.                         }  
  113.                     }  
  114.                 }  
  115.                 return dataTable;  
  116.             }  
  117.             catch (Exception)  
  118.             {  
  119.                 if (fs != null)  
  120.                 {  
  121.                     fs.Close();  
  122.                 }  
  123.                 returnnull;  
  124.             }  
  125.         }  
  126.     }  
  127. }  

三、結果


四、寫入excel類

  1. publicstaticbool DataTableToExcel(DataTable dt)  
  2.         {  
  3.             bool result = false;  
  4.             IWorkbook workbook = null;  
  5.             FileStream fs = null;  
  6.             IRow row = null;  
  7.             ISheet sheet = null;  
  8.             ICell cell = null;  
  9.             try
  10. 相關推薦

    C#NPOI操作excel讀取寫入excel

    一、下載引用 下載需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(offic

    C#npoi操作Excel[版本2.0.1讀寫2003、2007格式]

           public static void test1()        {            NpoiHelper np = new NpoiHelper();            DataTable dt1 = np.ReadExcel(AppDoma

    C++讀取寫入檔案

    C++之讀取和寫入檔案 在C++中使用std::ifstream來讀取檔案, 使用std::ofstream來寫入檔案,比如txt, yaml等檔案。 讀取檔案 #include <string> #include <fstream> std::string file_name

    java對txtexcel讀取寫入

    txt工具類: package com.rj.bd.xm; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInpu

    python讀取寫入csv文件

    pri style faq port bsp lee src jpg int 寫入csv文件源碼: 1 #輸出數據寫入CSV文件 2 import csv 3 data = [ 4 ("Mike", "male", 24), 5 ("Lee",

    Excel:使用java進行對excel讀取寫入

    excel:表格 可以作為一個數據庫使用 Pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht

    Unity Excel 檔案讀取寫入

    但是在使用的過程中還是碰到了不少的問題,在這裡總結一下,希望能對看到此處的朋友一個幫助。 1.Excel的讀取 Excel檔案 需要新增的名稱空間 using Excel; 讀取方法 using UnityEngine; using Excel;

    Python讀取寫入Excel檔案

    製作Excel表 常用方法說明 Workbook類 Workbook類建立一個XlswWrite的Workbook物件,相當於建立一個excel表 And_worksheet()用來建立工作表,預設為sheet1 Add_format():建立一個新的格式物件來格式化單元格,例如bold=

    Python讀取寫入Excel文件

    col mil cal 新的 ima 單元格 nbsp src 默認 制作Excel表 常用方法說明 Workbook類 Workbook類創建一個XlswWrite的Workbook對象,相當於創建一個excel表 And_worksheet()用來創建工作表,默認為

    Python3 讀取寫入excel xlsx檔案 使用openpyxl

    python處理excel已經有大量包,主流代表有:•xlwings:簡單強大,可替代VBA•openpyxl:簡單易用,功能廣泛•pandas:使用需要結合其他庫,資料處理是pandas立身之本•win32com:不僅僅是excel,可以處理office;不過它相當於是 w

    Java程式碼:用jxl實現excel讀取寫入

    建立的實體類 package com.jxl; public class Users {private Integer id;private String name;private String pwd;public Users() {super();// TODO Aut

    使用JAVA讀取寫入EXCEL檔案

    首先要下載 poi包和jxl包 讀取部分: import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNot

    Python讀取寫入Excel檔案[整]

    學習用Python處理Excel檔案,這裡主要用xlrd和xlwt模組,用前需要安裝!本文是來自幾篇部落格和官網tutorial的整理,主要是一個入門。更多的處理Excel的方法請到官網學習,連結為: 另外,幾篇部落格的參考資料: A:Excel資料的型

    C# NPOI 庫讀寫 Excel 文件的方法【摘】

    prot case enter this num ack npoi 工作薄 解鎖 原作:淡水網誌 NPOI 是開源的 POI 項目的.NET版,可以用來讀寫Excel,Word,PPT文件。在處理Excel文件上,NPOI 可以同時兼容 xls 和 xlsx。官網提供了一份

    java操作excel需要的配置以及讀取寫入方法

    參考連結: https://blog.csdn.net/seven__________7/article/details/53338300 https://blog.csdn.net/lu1005287365/article/details/51704774 下載poi模組最新版本,連結

    C#利用NPOI操作Excel(單元格設定)

    一.合併單元格 NOPI支援對單元格進行合併,還有單元格格式設定! 注意: 在進行單元格合併時必須先建立單元格 1.合併單元格語句: sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 3));//起始行,終止

    C# 使用NPOI操作Excel檔案

    什麼是NPOI? What’s NPOI This project is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source p

    C#使用NPOI操作Excel錯誤解決

    問題:未能載入檔案或程式集“ICSharpCode.SharpZipLib, Version=0.86.0.518, Culture=neutral, PublicKeyToken=1b03e6acf116 解決方案: 1:發現沒有引用此dll,在專案的package

    NPOI元件實現EXCEL大資料的讀取寫入

          public bool DataToExcel(DataTable SourceDataTable )         {             if (SourceDataTable == null) return false;             if (SourceDataTable.

    C#對類的序列化反序列化操作

    序列化和反序列化操作: 作用:實現不借助資料庫持久化的儲存資料。 實現步驟: 1.匯入名稱空間 using System.IO;//IO流實現檔案的讀寫 using System.Runtime.Serialization.Formatters