Questo articolo è un articolo speculare di traduzione automatica, clicca qui per saltare all'articolo originale.

Vista: 114413|Risposta: 15

[Fonte] . Operazione NPOI di lettura e scrittura plug-in Excel per Net

[Copiato link]
Pubblicato su 21/09/2015 18:45:03 | | |

1. L'intera tabella Excel si chiama worksheet: WorkBook, e contiene una pagina (worksheet): Sheet; File: Row; Cella.

2. NPOI è la versione C# di POI, e l'indice delle righe e delle colonne NPOI parte da 0

3. Esistono due formati per la lettura di Excel, uno HSSF e l'altro XSSF. Le differenze tra HSSF e XSSF sono le seguenti:
HSSF è l'implementazione puramente Java del formato Excel '97(-2007) del progetto POI.
XSSF è l'implementazione pura Java del Progetto POI del formato di file Excel 2007 OOXML (.xlsx).
Cioè, HSSF è applicabile alle versioni precedenti al 2007, e XSSF è applicabile a quelle dal 2007 e successive.

Di seguito è un esempio di utilizzo di NPOI per leggere e scrivere Excel: la funzione di ExcelHelper è scrivere dati da una DataTable su Excel, o leggere dati da Excel su una DataTable.

Corso ExcelHelper:

  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. }
Copia codice

NPOI 2.2.0.0.part01.rar (1 MB, Numero di download: 13)

NPOI 2.2.0.0.part02.rar (1 MB, Numero di download: 11) NPOI 2.2.0.0.part03.rar (1 MB, Numero di download: 6) NPOI 2.2.0.0.part04.rar (552.54 KB, Numero di download: 1)







Precedente:[Originale] Strumento di decrittografia Unicode che inizia con &quot;\u&quot;
Prossimo:Un modello di "progetto di laurea" dedicato al diploma di software di informatica
 Padrone di casa| Pubblicato su 01/11/2018 12:58:33 |
 Padrone di casa| Pubblicato su 14/05/2021 17:27:51 |
Pubblicato su 17/09/2021 13:58:09 |
Piccola Pubblicato il 17-09-2021 12:35
Fai il bug e risolvi tu stesso

L'indice è fuori ambito, non è altro che la tua datatable ha un totale di 10 righe di dati, leggi l'undicesima riga, oppure hai un totale di 5 ...

Il codice di esempio riceverà questo errore senza il bool dell'intestazione isFirstRowColumn=false, e se è con l'intestazione, andrà bene
Pubblicato su 22/09/2015 02:45:27 |
~~~~~~~~~~~~~~~~~~~~~~~~~
Pubblicato su 02/05/2018 16:08:02 |
Questo post è stato modificato l'ultima volta da QWERTYU il 2018-5-2 alle 16:52

Errore di esecuzione: Non si può ottenere un valore di testo da una cella numerica Soluzione:Formattazione delle celle

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


Pubblicato su 29/06/2019 16:03:00 |
Grazie, grazie, grazie mille
Pubblicato su 12/09/2021 10:12:16 |

Implementa semplici aggiunte, cancellazioni e modifiche alle pagine di ricerca
Pubblicato su 17/09/2021 09:32:23 |
Dai un'occhiata
Pubblicato su 17/09/2021 09:49:37 |
Eccezione lanciata: "System.IndexOutOfRangeException" (in System.Data.dll)
Exception: 无法找到列 0。
 Padrone di casa| Pubblicato su 17/09/2021 09:55:07 |
fyxh66 pubblicato il 17-09-2021 alle 09:49
Eccezione lanciata: "System.IndexOutOfRangeException" (in System.Data.dll)
Exception: 无法找到列 0。 ...

L'indice è fuori ambito

Più tardi ti darò un nuovo articolo come riferimento
Disconoscimento:
Tutto il software, i materiali di programmazione o gli articoli pubblicati dalla Code Farmer Network sono destinati esclusivamente all'apprendimento e alla ricerca; I contenuti sopra elencati non devono essere utilizzati per scopi commerciali o illegali, altrimenti gli utenti dovranno sostenere tutte le conseguenze. Le informazioni su questo sito provengono da Internet, e le controversie sul copyright non hanno nulla a che fare con questo sito. Devi eliminare completamente i contenuti sopra elencati dal tuo computer entro 24 ore dal download. Se ti piace il programma, ti preghiamo di supportare software autentico, acquistare la registrazione e ottenere servizi autentici migliori. In caso di violazione, vi preghiamo di contattarci via email.

Mail To:help@itsvse.com