1. The entire Excel table is called a worksheet: WorkBook (workbook), and it contains pages (worksheets): Sheet; Row: Row; Cell.
2. NPOI is the C# version of POI. The index of the row and column of NPOI starts from 0
3. POI reads Excel in two formats, one is HSSF and the other is XSSF. The difference between HSSF and XSSF is 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.
Namely: HSSF Applicable to versions prior to 2007, XSSF applies to versions 2007 and above.
The following is an example of using NPOI to read and write Excel: The function encapsulated by ExcelHelper is mainly to write data from DataTable to Excel, or to read data from Excel to a DataTable.
ExcelHelper class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using System.IO; using System.Data; namespace NetUtilityLib { public class ExcelHelper : IDisposable { private string fileName = null; //file name private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; public ExcelHelper(string fileName) { this.fileName = fileName; disposed = false; } /// <summary> /// Import DataTable data into excel /// </summary> /// <param name="data">Data to import</param> /// <param name="isColumnWritten">Does the column name of the DataTable want to be imported</param> /// <param name="sheetName">The name of the sheet of excel to be imported</param> /// <returns>Number of rows of imported data (the row containing the column name)</returns> public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //write the column name of the DataTable { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } workbook.Write(fs); //Write to excel return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } /// <summary> /// Import data from excel into DataTable /// </summary> /// <param name="sheetName">excel sheet name</param> /// <param name="isFirstRowColumn">Whether the first row is the column name of the DataTable</param> /// <returns>Returned DataTable</returns> public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //If the sheet corresponding to the specified sheetName is not found, try to get the first sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //The number of the last cell in a row is the total number of columns if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } // last column label int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //Row with no data defaults to null DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //Similarly, cells without data are null by default dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (fs != null) fs.Close(); } fs = null; disposed = true; } } } }
Test code:
Check out this article, which is highly read, and update my other version using Aspose.Cells:
PS: Aspose is charged
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using Aspose.Cells; namespace NetUtilityLib { public static class ExcelHelper { public static int DataTableToExcel(DataTable data, string fileName, string sheetName, bool isColumnNameWritten) { int num = -1; try { Workbook workBook; Worksheet worksheet = null; if (File.Exists(fileName)) workBook = new Workbook(fileName); else workBook = new Workbook(); if (sheetName == null) { if (workBook.Worksheets.Count > 0) { worksheet = workBook.Worksheets[0]; } else { sheetName = "Sheet1"; workBook.Worksheets.RemoveAt(sheetName); worksheet = workBook.Worksheets.Add(sheetName); } } if (worksheet != null) { worksheet.Cells.Clear(); num = worksheet.Cells.ImportDataTable(data, isColumnNameWritten, 0, 0, false); workBook.Save(fileName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return num; } public static void AddOneRowToExcel(DataRow dataRow, string fileName, string sheetName) { try { Workbook workBook; if (File.Exists(fileName)) workBook = new Workbook(fileName); else workBook = new Workbook(); Worksheet worksheet=null; if (sheetName == null) { worksheet = workBook.Worksheets[0]; } else { worksheet = workBook.Worksheets[sheetName]; } if (worksheet != null) { worksheet.Cells.ImportDataRow(dataRow, worksheet.Cells.MaxDataRow + 1,0); //worksheet.Cells.ImportArray(dataArray, worksheet.Cells.MaxDataRow+1, 0, false); workBook.Save(fileName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumnName) { DataTable data = new DataTable(); try { Workbook workbook = null; FileInfo fileInfo = new FileInfo(fileName); if (fileInfo.Extension.ToLower().Equals(".xlsx")) workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Xlsx)); else if (fileInfo.Extension.ToLower().Equals(".xls")) workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Excel97To2003)); if (workbook != null) { Worksheet worksheet = null; if (sheetName != null) { worksheet = workbook.Worksheets[sheetName]; } else { worksheet = workbook.Worksheets[0]; } if (worksheet != null) { data = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow+1, worksheet.Cells.MaxColumn+1, isFirstRowColumnName); return data; } } else { return data; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return data; } } }
Excel related DLL download: NPOI-Lib.rar
1. NPOI download address: http://npoi.codeplex.com/releases/view/38113
2. Recommended series of NPOI learning tutorials: http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html
refer to:
http://www.cnblogs.com/Erik_Xu/archive/2012/06/08/2541957.html
http://www.cnblogs.com/linzheng/archive/2010/12/20/1912137.html
http://www.cnblogs.com/knowledgesea/archive/2012/11/16/2772547.html