http://blog.csdn.net/heyangyi_19940703/article/details/52292755

http://www.cnblogs.com/zhengjuzhuan/archive/2010/02/01/1661103.html

http://www.cnblogs.com/stone_w/archive/2012/08/02/2620528.html

http://www.cnblogs.com/restran/p/3889479.html

http://blog.csdn.net/zjlovety/article/details/51384857

http://www.xuebuyuan.com/2116725.html

http://www.cnblogs.com/CallmeYhz/p/4997691.html

/// <summary>

/// 使用NPOI操作Excel,无需Office COM组件

/// Created By 囧月 http://lwme.cnblogs.com

/// 部分代码取自http://msdn.microsoft.com/zh-tw/ee818993.aspx

/// NPOI是POI的.NET移植版本,目前稳定版本中仅支持对xls文件(Excel 97-2003)文件格式的读写

/// NPOI官方网站http://npoi.codeplex.com/

/// </summary>

public class ExcelRender

{

    /// <summary>

    /// 根据Excel列类型获取列的值

    /// </summary>

    /// <param name="cell">Excel列</param>

    /// <returns></returns>

    private static string GetCellValue(ICell cell)

    {

        if (cell == null)

            return string.Empty;

        switch (cell.CellType)

        {

            case CellType.BLANK:

                return string.Empty;

            case CellType.BOOLEAN:

                return cell.BooleanCellValue.ToString();

            case CellType.ERROR:

                return cell.ErrorCellValue.ToString();

            case CellType.NUMERIC:

            case CellType.Unknown:

            default:

                return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number

            case CellType.STRING:

                return cell.StringCellValue;

            case CellType.FORMULA:

                try

                {

                    HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);

                    e.EvaluateInCell(cell);

                    return cell.ToString();

                }

                catch

                {

                    return cell.NumericCellValue.ToString();

                } 

        }

    }

    /// <summary>

    /// 自动设置Excel列宽

    /// </summary>

    /// <param name="sheet">Excel表</param>

    private static void AutoSizeColumns(ISheet sheet)

    {

        if (sheet.PhysicalNumberOfRows > 0)

        {

            IRow headerRow = sheet.GetRow(0);

            for (int i = 0, l = headerRow.LastCellNum; i < l; i++)

            {

                sheet.AutoSizeColumn(i);

            }

        }

    }

    /// <summary>

    /// 保存Excel文档流到文件

    /// </summary>

    /// <param name="ms">Excel文档流</param>

    /// <param name="fileName">文件名</param>

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

        }

    }

    /// <summary>

    /// 输出文件到浏览器

    /// </summary>

    /// <param name="ms">Excel文档流</param>

    /// <param name="context">HTTP上下文</param>

    /// <param name="fileName">文件名</param>

    private 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());

    }

    /// <summary>

    /// DataReader转换成Excel文档流

    /// </summary>

    /// <param name="reader"></param>

    /// <returns></returns>

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

                    }

                    AutoSizeColumns(sheet);

                    workbook.Write(ms);

                    ms.Flush();

                    ms.Position = 0;

                }

            }

        }

        return ms;

    }

    /// <summary>

    /// DataReader转换成Excel文档流,并保存到文件

    /// </summary>

    /// <param name="reader"></param>

    /// <param name="fileName">保存的路径</param>

    public static void RenderToExcel(IDataReader reader, string fileName)

    {

        using (MemoryStream ms = RenderToExcel(reader))

        {

            SaveToFile(ms, fileName);

        }

    }

    /// <summary>

    /// DataReader转换成Excel文档流,并输出到客户端

    /// </summary>

    /// <param name="reader"></param>

    /// <param name="context">HTTP上下文</param>

    /// <param name="fileName">输出的文件名</param>

    public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)

    {

        using (MemoryStream ms = RenderToExcel(reader))

        {

            RenderToBrowser(ms, context, fileName);

        }

    }

    /// <summary>

    /// DataTable转换成Excel文档流

    /// </summary>

    /// <param name="table"></param>

    /// <returns></returns>

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

                    }

                    AutoSizeColumns(sheet);

                    workbook.Write(ms);

                    ms.Flush();

                    ms.Position = 0;

                }

            }

        }

        return ms;

    }

    /// <summary>

    /// DataTable转换成Excel文档流,并保存到文件

    /// </summary>

    /// <param name="table"></param>

    /// <param name="fileName">保存的路径</param>

    public static void RenderToExcel(DataTable table, string fileName)

    {

        using (MemoryStream ms = RenderToExcel(table))

        {

            SaveToFile(ms, fileName);

        }

    }

    /// <summary>

    /// DataTable转换成Excel文档流,并输出到客户端

    /// </summary>

    /// <param name="table"></param>

    /// <param name="response"></param>

    /// <param name="fileName">输出的文件名</param>

    public static void RenderToExcel(DataTable table, HttpContext context, string fileName)

    {

        using (MemoryStream ms = RenderToExcel(table))

        {

            RenderToBrowser(ms, context, fileName);

        }

    }

    /// <summary>

    /// Excel文档流是否有数据

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <returns></returns>

    public static bool HasData(Stream excelFileStream)

    {

        return HasData(excelFileStream, 0);

    }

    /// <summary>

    /// Excel文档流是否有数据

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="sheetIndex">表索引号,如第一个表为0</param>

    /// <returns></returns>

    public static bool HasData(Stream excelFileStream, int sheetIndex)

    {

        using (excelFileStream)

        {

            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))

            {

                if (workbook.NumberOfSheets > 0)

                {

                    if (sheetIndex < workbook.NumberOfSheets)

                    {

                        using (ISheet sheet = workbook.GetSheetAt(sheetIndex))

                        {

                            return sheet.PhysicalNumberOfRows > 0;

                        }

                    }

                }

            }

        }

        return false;

    }

    /// <summary>

    /// Excel文档流转换成DataTable

    /// 第一行必须为标题行

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="sheetName">表名称</param>

    /// <returns></returns>

    public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)

    {

        return RenderFromExcel(excelFileStream, sheetName, 0);

    }

    /// <summary>

    /// Excel文档流转换成DataTable

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="sheetName">表名称</param>

    /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>

    /// <returns></returns>

    public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)

    {

        DataTable table = null;

        using (excelFileStream)

        {

            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))

            {

                using (ISheet sheet = workbook.GetSheet(sheetName))

                {

                    table = RenderFromExcel(sheet, headerRowIndex);

                }

            }

        }

        return table;

    }

    /// <summary>

    /// Excel文档流转换成DataTable

    /// 默认转换Excel的第一个表

    /// 第一行必须为标题行

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <returns></returns>

    public static DataTable RenderFromExcel(Stream excelFileStream)

    {

        return RenderFromExcel(excelFileStream, 0, 0);

    }

    /// <summary>

    /// Excel文档流转换成DataTable

    /// 第一行必须为标题行

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="sheetIndex">表索引号,如第一个表为0</param>

    /// <returns></returns>

    public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)

    {

        return RenderFromExcel(excelFileStream, sheetIndex, 0);

    }

    /// <summary>

    /// Excel文档流转换成DataTable

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="sheetIndex">表索引号,如第一个表为0</param>

    /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>

    /// <returns></returns>

    public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)

    {

        DataTable table = null;

        using (excelFileStream)

        {

            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))

            {

                using (ISheet sheet = workbook.GetSheetAt(sheetIndex))

                {

                    table = RenderFromExcel(sheet, headerRowIndex);

                }

            }

        }

        return table;

    }

    /// <summary>

    /// Excel表格转换成DataTable

    /// </summary>

    /// <param name="sheet">表格</param>

    /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>

    /// <returns></returns>

    private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)

    {

        DataTable table = new DataTable();

        IRow headerRow = sheet.GetRow(headerRowIndex);

        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;

    }

    /// <summary>

    /// Excel文档导入到数据库

    /// 默认取Excel的第一个表

    /// 第一行必须为标题行

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="insertSql">插入语句</param>

    /// <param name="dbAction">更新到数据库的方法</param>

    /// <returns></returns>

    public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)

    {

        return RenderToDb(excelFileStream, insertSql, dbAction, 0, 0);

    }

    public delegate int DBAction(string sql, params IDataParameter[] parameters);

    /// <summary>

    /// Excel文档导入到数据库

    /// </summary>

    /// <param name="excelFileStream">Excel文档流</param>

    /// <param name="insertSql">插入语句</param>

    /// <param name="dbAction">更新到数据库的方法</param>

    /// <param name="sheetIndex">表索引号,如第一个表为0</param>

    /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>

    /// <returns></returns>

    public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)

    {

        int rowAffected = 0;

        using (excelFileStream)

        {

            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))

            {

                using (ISheet sheet = workbook.GetSheetAt(sheetIndex))

                {

                    StringBuilder builder = new StringBuilder();

                    IRow headerRow = sheet.GetRow(headerRowIndex);

                    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;

    }

}

NPOI相关资料的更多相关文章

  1. 全文检索解决方案(lucene工具类以及sphinx相关资料)

    介绍两种全文检索的技术. 1.  lucene+ 中文分词(IK) 关于lucene的原理,在这里可以得到很好的学习. http://www.blogjava.net/zhyiwww/archive/ ...

  2. React Test相关资料

    karma 前端测试驱动器,生产测试报告,多个浏览器 mocha js的测试框架,相当于junit chai,单元测试的断言库,提供expect shudl assert enzyme sinon.j ...

  3. iOS10以及xCode8相关资料收集

    兼容iOS 10 资料整理笔记 源文:http://www.jianshu.com/p/0cc7aad638d9 1.Notification(通知) 自从Notification被引入之后,苹果就不 ...

  4. Nao 类人机器人 相关资料

    Nao 类人机器人 相关资料: 1.兄妹 PEPPER :在山东烟台生产,http://www.robot-china.com/news/201510/30/26564.html 2.国内机器人领先公 ...

  5. GBrowse配置相关资料

    GBrowse配置相关资料(形状.颜色.配置.gff3) http://gmod.org/wiki/Glyphs_and_Glyph_Optionshttp://gmod.org/wiki/GBrow ...

  6. AssetBundle机制相关资料收集

    原地址:http://www.cnblogs.com/realtimepixels/p/3652075.html AssetBundle机制相关资料收集 最近网友通过网站搜索Unity3D在手机及其他 ...

  7. 转:基于IOS上MDM技术相关资料整理及汇总

    一.MDM相关知识: MDM (Mobile Device Management ),即移动设备管理.在21世纪的今天,数据是企业宝贵的资产,安全问题更是重中之重,在移动互联网时代,员工个人的设备接入 ...

  8. smb相关资料

    smb相关资料 看资料就上维基 https://en.wikipedia.org/wiki/Server_Message_Block#Implementation http://www.bing.co ...

  9. Linux命令学习总结之rmdir命令的相关资料可以参考下

    这篇文章主要介绍了Linux命令学习总结之rmdir命令的相关资料,需要的朋友可以参考下(http://www.nanke0834.com) 命令简介: rmdir命令用用来删除空目录,如果目录非空, ...

随机推荐

  1. i春秋“百度杯”CTF比赛 十月场-Vld(单引号逃逸+报错注入)

    题目源代码给出了提示index.php.txt,打开拿到了一段看不太懂得东西. 图片标注的有flag1,flag2,flag3,同时还有三段字符,然后还出现了_GET,脑洞一一点想到访问 ?flag1 ...

  2. Android程序员提加薪被拒,刷2000题跳槽涨薪50%!

    为什么想跳槽? 简单说一下当时的状况,我在这家公司做了两年多,这两年多完成了一个大项目,作为开发的核心主力,开发压力很大,特别是项目上线前的几个月是非常辛苦,几乎每晚都要加班到12点以后,周末最多只有 ...

  3. Nacos 权限控制介绍及实战

    方案背景 Nacos自开源依赖,权限控制一直需求比较强烈,这也反应了用户需求将Nacos部署到生产环境的需求.最新发布的Nacos 1.2.0版本已经支持了服务发现和配置管理的权限控制,保障用户安全上 ...

  4. 跟我一起写 Makefile(六)

    书写命令 ---- 每条规则中的命令和操作系统Shell的命令行是一致的.make会一按顺序一条一条的执行命令,每条命令的开头必须以[Tab]键开头,除非,命令是紧跟在依赖规则后面的分号后的.在命令行 ...

  5. Shellshock 破壳漏洞 Writeup

    破壳漏洞 CVE编号:CVE-2014-6271 题目URL:http://www.whalwl.site:8029/ 提示:flag在服务器根目录 ShellShock (CVE-2014-6271 ...

  6. pikachu Files Inclusion

    文件包含分为远程文件包含和远程文件包含 比如程序员为了提高效率让代码看起来简洁,会使用包含函数的功能,写多个文件 之后需要了进行调用,比如.c写了很多个函数分别在不同的文件里,用的时候直接 引用文件即 ...

  7. Jetpack Compose学习(2)——文本(Text)的使用

    原文: Jetpack Compose学习(2)--文本(Text)的使用 | Stars-One的杂货小窝 对于开发来说,文字最为基础的组件,我们先从这两个使用开始吧 本篇涉及到Kotlin和DSL ...

  8. 针对Hbuilderx内置终端无法输入问题,总结了三种方法供大家参考

    下图,是内置终端无法输入的现象(本人使用的第三种方案,解决了该问题) 第一种解决方案,也是网上推荐最多的方案: 打开Hbuilder安装路径下插件文件夹中的main.js文件:HBuilderX\pl ...

  9. 0x800b010a 证书

    无论是装微软的什么应用,只要报这个错误,下载这个证书: http://download.microsoft.com/download/2/4/8/248D8A62-FCCD-475C-85E7-6ED ...

  10. .Net Framwork /.Net Core 发布为NuGet包

    一.使用NuGet发布包 下载NuGet命令行工具: https://dist.nuget.org/win-x86-commandline/v5.8.0/nuget.exe 下载NuGet Packa ...