四联光电智能照明论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2244|回复: 0
打印 上一主题 下一主题

NPOI读写Excel

[复制链接]
  • TA的每日心情
    开心
    2022-6-10 09:59
  • 366

    主题

    741

    帖子

    9649

    积分

    超级版主

    Rank: 8Rank: 8

    积分
    9649
    跳转到指定楼层
    楼主
    发表于 2016-11-3 12:02:04 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    原文地址:http://www.cnblogs.com/luxiaoxun/p/3374992.html

    1、整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet;行:Row;单元格Cell。

    2、NPOI是POI的C#版本,NPOI的行和列的index都是从0开始

    3、POI读取Excel有两种格式一个是HSSF,另一个是XSSF。 HSSF和XSSF的区别如下:
    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.
    即:HSSF适用2007以前的版本,XSSF适用2007版本及其以上的。

    下面是用NPOI读写Excel的例子:ExcelHelper封装的功能主要是把DataTable中数据写入到Excel中,或者是从Excel读取数据到一个DataTable中。

    ExcelHelper类:

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

    10. namespace NetUtilityLib
    11. {
    12.     public class ExcelHelper : IDisposable
    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.                         
    144.                         DataRow dataRow = data.NewRow();
    145.                         for (int j = row.FirstCellNum; j < cellCount; ++j)
    146.                         {
    147.                             if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
    148.                                 dataRow[j] = row.GetCell(j).ToString();
    149.                         }
    150.                         data.Rows.Add(dataRow);
    151.                     }
    152.                 }

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

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

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

    175.                 fs = null;
    176.                 disposed = true;
    177.             }
    178.         }
    179.     }
    180. }
    复制代码

    测试代码:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Data;

    6. namespace NPOIExcelExample
    7. {
    8.     class Program
    9.     {
    10.         static DataTable GenerateData()
    11.         {
    12.             DataTable data = new DataTable();
    13.             for (int i = 0; i < 5; ++i)
    14.             {
    15.                 data.Columns.Add("Columns_" + i.ToString(), typeof(string));
    16.             }

    17.             for (int i = 0; i < 10; ++i)
    18.             {
    19.                 DataRow row = data.NewRow();
    20.                 row["Columns_0"] = "item0_" + i.ToString();
    21.                 row["Columns_1"] = "item1_" + i.ToString();
    22.                 row["Columns_2"] = "item2_" + i.ToString();
    23.                 row["Columns_3"] = "item3_" + i.ToString();
    24.                 row["Columns_4"] = "item4_" + i.ToString();
    25.                 data.Rows.Add(row);
    26.             }
    27.             return data;
    28.         }

    29.         static void PrintData(DataTable data)
    30.         {
    31.             if (data == null) return;
    32.             for (int i = 0; i < data.Rows.Count; ++i)
    33.             {
    34.                 for (int j = 0; j < data.Columns.Count; ++j)
    35.                     Console.Write("{0} ", data.Rows[i][j]);
    36.                 Console.Write("\n");
    37.             }
    38.         }

    39.         static void TestExcelWrite(string file)
    40.         {
    41.             try
    42.             {
    43.                 using (ExcelHelper excelHelper = new ExcelHelper(file))
    44.                 {
    45.                     DataTable data = GenerateData();
    46.                     int count = excelHelper.DataTableToExcel(data, "MySheet", true);
    47.                     if (count > 0)
    48.                         Console.WriteLine("Number of imported data is {0} ", count);
    49.                 }
    50.             }
    51.             catch (Exception ex)
    52.             {
    53.                 Console.WriteLine("Exception: " + ex.Message);
    54.             }
    55.         }

    56.         static void TestExcelRead(string file)
    57.         {
    58.             try
    59.             {
    60.                 using (ExcelHelper excelHelper = new ExcelHelper(file))
    61.                 {
    62.                     DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);
    63.                     PrintData(dt);
    64.                 }
    65.             }
    66.             catch (Exception ex)
    67.             {
    68.                 Console.WriteLine("Exception: " + ex.Message);
    69.             }
    70.         }

    71.         static void Main(string[] args)
    72.         {
    73.             string file = "..\\..\\myTest.xlsx";
    74.             TestExcelWrite(file);
    75.             TestExcelRead(file);
    76.         }
    77.     }
    78. }
    复制代码

    签于这篇文章阅读量较高,更新一下我使用Aspose.Cells的另一个版本:

    PS:Aspose是要收费的

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Data;
    4. using System.IO;
    5. using System.Linq;
    6. using System.Text;
    7. using Aspose.Cells;

    8. namespace NetUtilityLib
    9. {
    10.     public static class ExcelHelper
    11.     {
    12.         public static int DataTableToExcel(DataTable data, string fileName, string sheetName, bool isColumnNameWritten)
    13.         {
    14.             int num = -1;
    15.             try
    16.             {
    17.                 Workbook workBook;
    18.                 Worksheet worksheet = null;

    19.                 if (File.Exists(fileName))
    20.                     workBook = new Workbook(fileName);
    21.                 else
    22.                     workBook = new Workbook();

    23.                 if (sheetName == null)
    24.                 {
    25.                     if (workBook.Worksheets.Count > 0)
    26.                     {
    27.                         worksheet = workBook.Worksheets[0];
    28.                     }
    29.                     else
    30.                     {
    31.                         sheetName = "Sheet1";
    32.                         workBook.Worksheets.RemoveAt(sheetName);
    33.                         worksheet = workBook.Worksheets.Add(sheetName);
    34.                     }
    35.                 }
    36.                 if (worksheet != null)
    37.                 {
    38.                     worksheet.Cells.Clear();
    39.                     num = worksheet.Cells.ImportDataTable(data, isColumnNameWritten, 0, 0, false);
    40.                     workBook.Save(fileName);
    41.                 }
    42.             }
    43.             catch (Exception ex)
    44.             {
    45.                 Console.WriteLine(ex.Message);
    46.             }

    47.             return num;
    48.         }

    49.         public static void AddOneRowToExcel(DataRow dataRow, string fileName, string sheetName)
    50.         {
    51.             try
    52.             {
    53.                 Workbook workBook;

    54.                 if (File.Exists(fileName))
    55.                     workBook = new Workbook(fileName);
    56.                 else
    57.                     workBook = new Workbook();

    58.                 Worksheet worksheet=null;

    59.                 if (sheetName == null)
    60.                 {
    61.                     worksheet = workBook.Worksheets[0];
    62.                 }
    63.                 else
    64.                 {
    65.                     worksheet = workBook.Worksheets[sheetName];
    66.                 }
    67.                 if (worksheet != null)
    68.                 {
    69.                     worksheet.Cells.ImportDataRow(dataRow, worksheet.Cells.MaxDataRow + 1,0);
    70.                     //worksheet.Cells.ImportArray(dataArray, worksheet.Cells.MaxDataRow+1, 0, false);
    71.                     workBook.Save(fileName);
    72.                 }
    73.             }
    74.             catch (Exception ex)
    75.             {
    76.                 Console.WriteLine(ex.Message);
    77.             }
    78.         }

    79.         public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumnName)
    80.         {
    81.             DataTable data = new DataTable();

    82.             try
    83.             {
    84.                 Workbook workbook = null;

    85.                 FileInfo fileInfo = new FileInfo(fileName);
    86.                 if (fileInfo.Extension.ToLower().Equals(".xlsx"))
    87.                     workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Xlsx));
    88.                 else if (fileInfo.Extension.ToLower().Equals(".xls"))
    89.                     workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Excel97To2003));
    90.                 if (workbook != null)
    91.                 {
    92.                     Worksheet worksheet = null;
    93.                     if (sheetName != null)
    94.                     {
    95.                         worksheet = workbook.Worksheets[sheetName];
    96.                     }
    97.                     else
    98.                     {
    99.                         worksheet = workbook.Worksheets[0];
    100.                     }
    101.                     if (worksheet != null)
    102.                     {
    103.                         data = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow+1, worksheet.Cells.MaxColumn+1,
    104.                             isFirstRowColumnName);

    105.                         return data;
    106.                     }
    107.                 }
    108.                 else
    109.                 {
    110.                     return data;
    111.                 }
    112.             }
    113.             catch (Exception ex)
    114.             {
    115.                 Console.WriteLine(ex.Message);
    116.             }

    117.             return data;
    118.         }
    119.     }
    120. }
    复制代码


    Excel相关DLL下载:NPOI-Lib.rar

    1.NPOI下载地址:http://npoi.codeplex.com/releases/view/38113
    2.NPOI学习系列教程推荐:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html


    参考:
    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/knowledge ... /11/16/2772547.html
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|Archiver|手机版|小黑屋|Silian Lighting+ ( 蜀ICP备14004521号-1 )

    GMT+8, 2024-5-17 14:31 , Processed in 1.078125 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2013 Comsenz Inc.

    快速回复 返回顶部 返回列表