This article is a mirror article of machine translation, please click here to jump to the original article.

View: 114413|Reply: 15

[Source] . NPOI read and write operation Excel table plug-in for Net

[Copy link]
Posted on 9/21/2015 6:45:03 PM | | |

1. The entire Excel table is called a worksheet: WorkBook, and it contains a page (worksheet): Sheet; Row: Row; Cell.

2. NPOI is the C# version of POI, and the index of NPOI's rows and columns starts from 0

3. There are two formats for POI reading Excel, one is HSSF and the other is XSSF. The differences between HSSF and XSSF are as follows:
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.
That is, HSSF is applicable to versions before 2007, and XSSF is applicable to 2007 and above.

The following is an example of using NPOI to read and write Excel: The function of ExcelHelper is to write data from a DataTable to Excel, or read data from Excel to a DataTable.

ExcelHelper class:

  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.XSSF.UserModel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Web;

  10. namespace HouPuStudent.Utility
  11. {
  12.     public class ExcelHelper
  13.     {
  14.         private string fileName = null; //文件名
  15.         private IWorkbook workbook = null;
  16.         private FileStream fs = null;
  17.         private bool disposed;

  18.         public ExcelHelper(string fileName)
  19.         {
  20.             this.fileName = fileName;
  21.             disposed = false;
  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.             fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  37.             if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  38.                 workbook = new XSSFWorkbook();
  39.             else if (fileName.IndexOf(".xls") > 0) // 2003版本
  40.                 workbook = new HSSFWorkbook();

  41.             try
  42.             {
  43.                 if (workbook != null)
  44.                 {
  45.                     sheet = workbook.CreateSheet(sheetName);
  46.                 }
  47.                 else
  48.                 {
  49.                     return -1;
  50.                 }

  51.                 if (isColumnWritten == true) //写入DataTable的列名
  52.                 {
  53.                     IRow row = sheet.CreateRow(0);
  54.                     for (j = 0; j < data.Columns.Count; ++j)
  55.                     {
  56.                         row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
  57.                     }
  58.                     count = 1;
  59.                 }
  60.                 else
  61.                 {
  62.                     count = 0;
  63.                 }

  64.                 for (i = 0; i < data.Rows.Count; ++i)
  65.                 {
  66.                     IRow row = sheet.CreateRow(count);
  67.                     for (j = 0; j < data.Columns.Count; ++j)
  68.                     {
  69.                         row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
  70.                     }
  71.                     ++count;
  72.                 }
  73.                 workbook.Write(fs); //写入到excel
  74.                 return count;
  75.             }
  76.             catch (Exception ex)
  77.             {
  78.                 Console.WriteLine("Exception: " + ex.Message);
  79.                 return -1;
  80.             }
  81.         }

  82.         /// <summary>
  83.         /// 将excel中的数据导入到DataTable中
  84.         /// </summary>
  85.         /// <param name="sheetName">excel工作薄sheet的名称</param>
  86.         /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  87.         /// <returns>返回的DataTable</returns>
  88.         public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
  89.         {
  90.             ISheet sheet = null;
  91.             DataTable data = new DataTable();
  92.             int startRow = 0;
  93.             try
  94.             {
  95.                 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  96.                 if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  97.                     workbook = new XSSFWorkbook(fs);
  98.                 else if (fileName.IndexOf(".xls") > 0) // 2003版本
  99.                     workbook = new HSSFWorkbook(fs);

  100.                 if (sheetName != null)
  101.                 {
  102.                     sheet = workbook.GetSheet(sheetName);
  103.                     if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  104.                     {
  105.                         sheet = workbook.GetSheetAt(0);
  106.                     }
  107.                 }
  108.                 else
  109.                 {
  110.                     sheet = workbook.GetSheetAt(0);
  111.                 }
  112.                 if (sheet != null)
  113.                 {
  114.                     IRow firstRow = sheet.GetRow(0);
  115.                     int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

  116.                     if (isFirstRowColumn)
  117.                     {
  118.                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  119.                         {
  120.                             ICell cell = firstRow.GetCell(i);
  121.                             if (cell != null)
  122.                             {
  123.                                 string cellValue = cell.StringCellValue;
  124.                                 if (cellValue != null)
  125.                                 {
  126.                                     DataColumn column = new DataColumn(cellValue);
  127.                                     data.Columns.Add(column);
  128.                                 }
  129.                             }
  130.                         }
  131.                         startRow = sheet.FirstRowNum + 1;
  132.                     }
  133.                     else
  134.                     {
  135.                         startRow = sheet.FirstRowNum;
  136.                     }

  137.                     //最后一列的标号
  138.                     int rowCount = sheet.LastRowNum;
  139.                     for (int i = startRow; i <= rowCount; ++i)
  140.                     {
  141.                         IRow row = sheet.GetRow(i);
  142.                         if (row == null) continue; //没有数据的行默认是null       

  143.                         DataRow dataRow = data.NewRow();
  144.                         for (int j = row.FirstCellNum; j < cellCount; ++j)
  145.                         {
  146.                             if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  147.                                 dataRow[j] = row.GetCell(j).ToString();
  148.                         }
  149.                         data.Rows.Add(dataRow);
  150.                     }
  151.                 }

  152.                 return data;
  153.             }
  154.             catch (Exception ex)
  155.             {
  156.                 Console.WriteLine("Exception: " + ex.Message);
  157.                 return null;
  158.             }
  159.         }

  160.         public void Dispose()
  161.         {
  162.             Dispose(true);
  163.             GC.SuppressFinalize(this);
  164.         }

  165.         protected virtual void Dispose(bool disposing)
  166.         {
  167.             if (!this.disposed)
  168.             {
  169.                 if (disposing)
  170.                 {
  171.                     if (fs != null)
  172.                         fs.Close();
  173.                 }

  174.                 fs = null;
  175.                 disposed = true;
  176.             }
  177.         }
  178.     }
  179. }
Copy code

NPOI 2.2.0.0.part01.rar (1 MB, Number of downloads: 13)

NPOI 2.2.0.0.part02.rar (1 MB, Number of downloads: 11) NPOI 2.2.0.0.part03.rar (1 MB, Number of downloads: 6) NPOI 2.2.0.0.part04.rar (552.54 KB, Number of downloads: 1)







Previous:[Original] Unicode encryption decryption tool starting with &quot;\u&quot;
Next:A "graduation project" template dedicated to graduating computer science software
 Landlord| Posted on 11/1/2018 12:58:33 PM |
 Landlord| Posted on 5/14/2021 5:27:51 PM |
Posted on 9/17/2021 1:58:09 PM |
Little slag Posted on 2021-9-17 12:35
Debug and solve it yourself

The index is out of scope, it is nothing more than your datatable has a total of 10 rows of data, you read the 11th row, or you have a total of 5 ...

The sample code will get this error without the header bool isFirstRowColumn=false, and if it is with the header, it will be fine
Posted on 9/22/2015 2:45:27 AM |
~~~~~~~~~~~~~~~~~~~~~~~~~
Posted on 5/2/2018 4:08:02 PM |
This post was last edited by QWERTYU on 2018-5-2 16:52

Run error: Cannot get a text value from a numeric cell Solution:Format the cells

   HSSFCell cell = row.getCell(keyIndex);
   cell.setCellType(HSSFCell.CELL_TYPE_STRING);


Posted on 6/29/2019 4:03:00 PM |
Thank you, thank you, thank you so much
Posted on 9/12/2021 10:12:16 AM |

Implement simple additions, deletions, and changes to search pages
Posted on 9/17/2021 9:32:23 AM |
Take a look
Posted on 9/17/2021 9:49:37 AM |
Exception thrown: "System.IndexOutOfRangeException" (in System.Data.dll)
Exception: 无法找到列 0。
 Landlord| Posted on 9/17/2021 9:55:07 AM |
fyxh66 posted on 2021-9-17 09:49
Exception thrown: "System.IndexOutOfRangeException" (in System.Data.dll)
Exception: 无法找到列 0。 ...

The index is out of scope

Later, I'll give you a new article for reference
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com