zoukankan      html  css  js  c++  java
  • 使用NPOI导入导出标准Excel

    尝试过非常多Excel导入导出方法。都不太理想,无意中逛到oschina时,发现了NPOI。无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文。

     

    曾使用过的方法

    1. 直接导出html,改动后缀名为.xls,这种方法有点像骗人的把戏。并且不能再导入
    2. 使用Jet OLEDB引擎来进行导入导出。全然使用sql语句来进行操作,缺点能控制的东西很有限,比方格式就难以控制
    3. 使用Office COM组件进行导入导出。对环境依赖性太强(如“检索 COM 类工厂…”错误);且须要通过打开Excel.exe进程进行操作。尽管能够通过关闭工作表以及Marshal.ReleaseComObject方法来释放资源。但依旧避免不了性能差。

     

    关于NPOI

    NPOIPOI项目的.NET版本号。是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,能够从http://npoi.codeplex.com/下载到它的最新版本号。

    它不使用Office COM组件(Microsoft.Office.Interop.XXX.dll),不须要安装Microsoft Office,支持对Office 97-2003的文件格式。功能比較强大。更具体的说明请看作者的博客或官方站点。

     

    它的下面一些特性让我相当喜欢:

    1. 支持对标准的Excel读写
    2. 支持对流(Stream)的读写 (而Jet OLEDB和Office COM都仅仅能针对文件)
    3. 支持大部分Office COM组件的经常使用功能
    4. 性能优异 (相对于前面的方法)
    5. 使用简单。易上手

    使用NPOI

    本文使用的是它当前的最新版本号1.2.4,此版本号的程序集缩减至2个:NPOI.dllIonic.Zip.dll,直接引用到项目中就可以。

    对于我们开发人员使用的对象主要位于NPOI.HSSF.UserModel空间下。主要有HSSFWorkbookHSSFSheetHSSFRowHSSFCell,相应的接口为位于NPOI.SS.UserModel空间下的IWorkbookISheetIRowICell,分别相应Excel文件、工作表、行、列。

     

    简单演示一下创建一个Workbook对象,加入一个工作表,在工作表中加入一行一列:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
     
    public class NPOIWrite
    {
        void CreateSheet()
        {
            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet("Sheet1");//创建工作表
            IRow row = sheet.CreateRow(0);//在工作表中加入一行
            ICell cell = row.CreateCell(0);//在行中加入一列
            cell.SetCellValue("test");//设置列的内容
        }
    }

     

    对应的读代替码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    using System.IO;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
     
    public class NPOIRead
    {
        void GetSheet(Stream stream)
        {
            IWorkbook workbook = new HSSFWorkbook(stream);//从流内容创建Workbook对象
            ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作表
            IRow row = sheet.GetRow(0);//获取工作表第一行
            ICell cell = row.GetCell(0);//获取行的第一列
            string value = cell.ToString();//获取列的值
        }
    }

     

    使用NPOI导出

    从DataTable读取内容来创建Workbook对象:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    public static MemoryStream RenderToExcel(DataTable table)
    {
        MemoryStream ms = new MemoryStream();
     
        using (table)
        {
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (ISheet sheet = workbook.CreateSheet())
                {
                    IRow headerRow = sheet.CreateRow(0);
     
                    // handling header.
                    foreach (DataColumn column in table.Columns)
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
     
                    // handling value.
                    int rowIndex = 1;
     
                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
     
                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }
     
                        rowIndex++;
                    }
     
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
            }
        }
        return ms;
    }

    假设看不惯DataTable,那么DataReader也行:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    public static MemoryStream RenderToExcel(IDataReader reader)
    {
        MemoryStream ms = new MemoryStream();
     
        using (reader)
        {
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (ISheet sheet = workbook.CreateSheet())
                {
                    IRow headerRow = sheet.CreateRow(0);
                    int cellCount = reader.FieldCount;
     
                    // handling header.
                    for (int i = 0; i < cellCount; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
                    }
     
                    // handling value.
                    int rowIndex = 1;
                    while (reader.Read())
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
     
                        for (int i = 0; i < cellCount; i++)
                        {
                            dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
                        }
     
                        rowIndex++;
                    }
     
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
            }
        }
        return ms;
    }

    以上代码把创建的Workbook对象保存到流中。能够通过下面方法输出到浏览器,或是保存到硬盘中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    static void SaveToFile(MemoryStream ms, string fileName)
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            byte[] data = ms.ToArray();
     
            fs.Write(data, 0, data.Length);
            fs.Flush();
     
            data = null;
        }
    }
     
    static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
    {
        if (context.Request.Browser.Browser == "IE")
            fileName = HttpUtility.UrlEncode(fileName);
        context.Response.AddHeader("Content-Disposition","attachment;fileName=" + fileName);
        context.Response.BinaryWrite(ms.ToArray());
    }

     

    使用NPOI导入

    须要注意的是,sheet.LastRowNum = sheet.PhysicalNumberOfRows - 1。这里可能存在BUG:当没有数据或仅仅有一行数据时sheet.LastRowNum为0,PhysicalNumberOfRows 表现正常

    这里读取流中的Excel来创建Workbook对象。并转换成DataTable:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    static DataTable RenderFromExcel(Stream excelFileStream)
    {
        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                using (ISheet sheet = workbook.GetSheetAt(0))//取第一个表
                {
                    DataTable table = new DataTable();
     
                    IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
     
                    //handling header.
                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                        table.Columns.Add(column);
                    }
     
                    for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dataRow = table.NewRow();
     
                        if (row != null)
                        {
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                    dataRow[j] = GetCellValue(row.GetCell(j));
                            }
                        }
     
                        table.Rows.Add(dataRow);
                    }
                    return table;
     
                }
            }
        }
    }

    或者是直接生成SQL语句来插入到数据库:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
    {
        int rowAffected = 0;
        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                using (ISheet sheet = workbook.GetSheetAt(0))//取第一个工作表
                {
                    StringBuilder builder = new StringBuilder();
     
                    IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
     
                    for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row != null)
                        {
                            builder.Append(insertSql);
                            builder.Append(" values (");
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'","''"));
                            }
                            builder.Length = builder.Length - 1;
                            builder.Append(");");
                        }
     
                        if ((i % 50 == 0 || i == rowCount) && builder.Length > 0)
                        {
                            //每50条记录一次批量插入到数据库
                            rowAffected += dbAction(builder.ToString());
                            builder.Length = 0;
                        }
                    }
                }
            }
        }
        return rowAffected;
    }

    这里的Excel可能没有数据,所以能够加一个方法来检測:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public static bool HasData(Stream excelFileStream)
    {
        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                if (workbook.NumberOfSheets > 0)
                {
                    using (ISheet sheet = workbook.GetSheetAt(0))
                    {
                        return sheet.PhysicalNumberOfRows > 0;
                    }
                }
            }
        }
        return false;
    }

     

    结尾

    好吧,不说啥了,放代码:点击下载

  • 相关阅读:
    ansible 通过跳板机发布服务
    etcd API 神坑
    golang 条件编译
    服务治理
    golang web服务器处理前端HTTP请求跨域的方法
    rebar使用
    Apache/Tomcat/JBOSS/Jetty/Nginx/WebLogic/WebSphere之间的区别区别
    运维专家写给年轻运维的6条人生忠告
    谷歌浏览器书签索引—知识的海洋都在里面
    关于认识、格局、多维度发展的感触
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6866868.html
Copyright © 2011-2022 走看看