Loading

NPOI读写Excel

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类:

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; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExcelHelper(string fileName)
        {
            this.fileName = fileName;
            disposed = false;
        }

        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</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) //写入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); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的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) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    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;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       
                        
                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                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;
            }
        }
    }
}

测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace NPOIExcelExample
{
    class Program
    {
        static DataTable GenerateData()
        {
            DataTable data = new DataTable();
            for (int i = 0; i < 5; ++i)
            {
                data.Columns.Add("Columns_" + i.ToString(), typeof(string));
            }

            for (int i = 0; i < 10; ++i)
            {
                DataRow row = data.NewRow();
                row["Columns_0"] = "item0_" + i.ToString();
                row["Columns_1"] = "item1_" + i.ToString();
                row["Columns_2"] = "item2_" + i.ToString();
                row["Columns_3"] = "item3_" + i.ToString();
                row["Columns_4"] = "item4_" + i.ToString();
                data.Rows.Add(row);
            }
            return data;
        }

        static void PrintData(DataTable data)
        {
            if (data == null) return;
            for (int i = 0; i < data.Rows.Count; ++i)
            {
                for (int j = 0; j < data.Columns.Count; ++j)
                    Console.Write("{0} ", data.Rows[i][j]);
                Console.Write("\n");
            }
        }

        static void TestExcelWrite(string file)
        {
            try
            {
                using (ExcelHelper excelHelper = new ExcelHelper(file))
                {
                    DataTable data = GenerateData();
                    int count = excelHelper.DataTableToExcel(data, "MySheet", true);
                    if (count > 0)
                        Console.WriteLine("Number of imported data is {0} ", count);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
        }

        static void TestExcelRead(string file)
        {
            try
            {
                using (ExcelHelper excelHelper = new ExcelHelper(file))
                {
                    DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);
                    PrintData(dt);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
        }

        static void Main(string[] args)
        {
            string file = "..\\..\\myTest.xlsx";
            TestExcelWrite(file);
            TestExcelRead(file);
        }
    }
}
View Code

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

PS:Aspose是要收费的

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相关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/knowledgesea/archive/2012/11/16/2772547.html

 

posted @ 2013-10-17 20:45  阿凡卢  阅读(148392)  评论(37编辑  收藏  举报