public class NPOIHelper
    {
        private HSSFWorkbook workbook;
        public static IWorkbook LoadFromFile(string filepath)
        {
            using (FileStream fi = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                return new HSSFWorkbook(fi);
            }
        }

public static ISheet CreateSheet(string sheetname, IWorkbook workbook)
        {
            return workbook.CreateSheet(sheetname);
        }

public ISheet WriteToTemplate<T>(IList<T> datalist, string sheetname, int fieldstartrowindex, int fieldstartcolindex, int datastartrowindex)           
        {
            return null;
        }

public NPOIHelper(string filetemplatepath)
        {
            workbook = (HSSFWorkbook)LoadFromFile(filetemplatepath);
       
        }

/// <summary>
        /// 将List对象转为SHEET
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sheetname"></param>
        /// <param name="data"></param>      
        /// <param name="titlerowindex">表头列</param>
        /// <param name="datarowindex">表数据列</param>
        /// <returns></returns>
        public int ConvertTOSheet<T>(string sheetname, IList<T> data,  int titlerowindex, int datarowindex)
           where T : new()
        {
            ISheet sheet = workbook.GetSheet(sheetname);
          
            IRow titlerow = sheet.GetRow(titlerowindex);
            int rowstartindex = titlerow.FirstCellNum;
            int rowlastindex = titlerow.LastCellNum;

IDictionary<int, string> fieldindexdic = new Dictionary<int, string>();
            for (int i = rowstartindex; i <= rowlastindex; i++)
            {
                ICell cell = titlerow.GetCell(i);
                if (cell != null)
                {
                    string fieldstr = cell.ToString();
                    if (!string.IsNullOrEmpty(fieldstr))
                    {
                        fieldindexdic.Add(cell.ColumnIndex, fieldstr.ToUpper());
                    }
                }
            }

IEnumerable<string> fieldtitle = fieldindexdic.Select(x => x.Value).Distinct();

IDictionary<string, PropertyInfo> pifdic = GetPropertyInfoDic<T>(fieldtitle);
            for (int i = 0; i < data.Count; i++)
            {
                IRow datarow = sheet.CreateRow(datarowindex + i);
                foreach (var titlekv in fieldindexdic)
                {
                    object dataobject = pifdic[titlekv.Value].GetValue(data[i], null);
                    if (dataobject != null)
                    {
                        ICell datacell = datarow.CreateCell(titlekv.Key);
                        datacell.SetCellValue(dataobject.ToString());
                    }
                }
            }
            return workbook.GetSheetIndex(sheet);
        }

public IDictionary<string, PropertyInfo> GetPropertyInfoDic<T>(IEnumerable<string> namelist)
            where T : new()
        {
            IDictionary<string, PropertyInfo> pifdic = new Dictionary<string, PropertyInfo>();
            PropertyInfo[] pifs = typeof(T).GetProperties();

IEnumerable<PropertyInfo> filedpifs = pifs.Where(x => namelist.Contains(x.Name.ToUpper()));
            foreach (var kv in filedpifs)
            {
                pifdic.Add(kv.Name.ToUpper(), kv);
            }
            return pifdic;
        }
        public void DeleteSheet(string sheetname)
        { 
             int sheetindex =  workbook.GetSheetIndex(sheetname);
             workbook.RemoveSheetAt(sheetindex);          
        }
        public void Write(Stream sm)
        {
            workbook.Write(sm);       
        }
        public void DeleteRow(string sheetname, int rowindex)
        {
            ISheet sheet = workbook.GetSheet(sheetname);
            IRow row = sheet.GetRow(rowindex);
            sheet.RemoveRow(row);       
        }

#region add by pcitdbt 2013/11/11

#region 将DataTable的数据读取成MemoryStream
        public static MemoryStream RenderToExcel(DataTable dt)
        {
            MemoryStream ms = new MemoryStream();
            using (dt)
            {
                //创建Workbook
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet(dt.TableName);
                //创建一个日期类型的格式
                ICellStyle dataStyle = book.CreateCellStyle();
                IDataFormat dataFormat = book.CreateDataFormat();
                dataStyle.DataFormat = dataFormat.GetFormat("yyyy-mm-dd");
                //创建表头
                IRow row = sheet.CreateRow(0);
                foreach (DataColumn col in dt.Columns)
                {
                    //给表头添加字段名字
                    row.CreateCell(col.Ordinal).SetCellValue(col.Caption);//Caption没有值则获取ColumnName
                    //设置列宽
                    sheet.SetColumnWidth(col.Ordinal, 30 * 110);
                }
                //创建数据行并添加值
                int rowIndex = 1;//标记数据行的位置
                foreach (DataRow dr in dt.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

//通过列来获取值
                    foreach (DataColumn column in dt.Columns)
                    {
                        //判断是否是DataTime类型
                        ICell newCell = dataRow.CreateCell(column.Ordinal);
                        string drValue = dr[column].ToString();
                        switch (column.DataType.ToString())
                        {
                            case "System.String"://字符串类型
                                newCell.SetCellValue(drValue);
                                break;
                            case "System.DateTime"://日期类型
                                DateTime dateV;
                                DateTime.TryParse(drValue, out dateV);
                                //newCell.SetCellValue(dateV);
                                newCell.SetCellValue(drValue);

newCell.CellStyle = dataStyle;//格式化显示
                                break;
                            case "System.Boolean"://布尔型
                                bool boolV = false;
                                bool.TryParse(drValue, out boolV);
                                newCell.SetCellValue(boolV);
                                break;
                            case "System.Int16"://整型
                            case "System.Int32":
                            case "System.Int64":
                            case "System.Byte":
                                int intV = 0;
                                int.TryParse(drValue, out intV);
                                newCell.SetCellValue(intV);
                                break;
                            case "System.Decimal"://浮点型
                            case "System.Double":
                                double doubV = 0;
                                double.TryParse(drValue, out doubV);
                                newCell.SetCellValue(doubV);
                                break;
                            case "System.DBNull"://空值处理
                                newCell.SetCellValue("");
                                break;
                            default:
                                newCell.SetCellValue("");
                                break;
                        }

}

//循环一行后i的值自增1
                    rowIndex++;
                }

book.Write(ms);
                ms.Flush();
                ms.Position = 0;//指定内存流的当前位置
              }

return ms;
        }
        #endregion

#region 将DataReader的数据转换成MemoryStream并返回
        public static MemoryStream RenderToExcel(IDataReader dataReader)
        {
            MemoryStream ms = new MemoryStream();
            using (dataReader)
            {
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet("数据表1");
                //创建表头
                IRow row = sheet.CreateRow(0);
                //列的数目
                int columnCount = dataReader.FieldCount;
                for (int i = 0; i < columnCount; i++)
                {
                    row.CreateCell(i).SetCellValue(dataReader.GetName(i));
                }

//创建数据行
                int rowIndex = 1;
                while (dataReader.Read())//dataReader只能一行一行地读取数据
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    for (int i = 0; i < columnCount; i++)
                    {

dataRow.CreateCell(i).SetCellValue(dataReader[i].ToString());
                    }

rowIndex++;
                }

book.Write(ms);
                ms.Flush();
                ms.Position = 0;

}

return ms;
        }

#endregion

#region 将流输出到指定的位置
        //保存输出到文件
        public 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;
            }
        }
        #endregion

#region 保存输出到浏览器
        public static void SaveToBrowser(MemoryStream ms, System.Web.HttpContext context, string fileName)
        {
            // 设置编码和附件格式
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.Charset = "";
            context.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" +System.Web.HttpUtility.UrlEncode(fileName, Encoding.UTF8));

//添加请求报文头
            //context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            context.Response.BinaryWrite(ms.ToArray());
            context.Response.End();
        }
        #endregion

#region NPOI读取Excel流的数据相关
        public DataTable ReadFromExcel(Stream excelStream)
        {
            DataTable dt = new DataTable();
            using (excelStream)
            {
                //创建WorkBook
                HSSFWorkbook book = new HSSFWorkbook(excelStream);
                ISheet sheet = book.GetSheetAt(0);//获取第一个表
                //获取第一行表头
                IRow headRow = sheet.GetRow(0);
                //列数
                int columnCount = headRow.LastCellNum;//LastCellNum=PhysicalNumberOfCells
                int rowCount = sheet.LastRowNum;//LastRowNum=PhysicalNumberOfCellsRow-1
                //创建DataTable的表头
                for (int i = headRow.FirstCellNum; i < columnCount; i++)
                {
                    DataColumn dc = new DataColumn(headRow.GetCell(i).StringCellValue.ToString());
                    dt.Columns.Add(dc);
                }
                //创建数据
                for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                {
                    //一行一行地创建
                    DataRow dr = dt.NewRow();
                    IRow dataRow = sheet.GetRow(i);
                    if (dataRow != null)
                    {
                        for (int j = headRow.FirstCellNum; j < columnCount; j++)
                        {
                            string cellValue = dataRow.GetCell(j).StringCellValue.ToString();
                            if (cellValue != "" || cellValue != null)
                            {
                                dr[j] = dataRow.GetCell(j).StringCellValue.ToString();
                            }

}

dt.Rows.Add(dr);
                    }

}

}

return dt;
        }

public static int RenderToDb(Stream excelFileStream, string insertSql)
        {
            int rowAffected = 0;
            using (excelFileStream)
            {
                HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
                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}',", row.GetCell(j).StringCellValue.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;
        }

public static bool HasData(Stream excelFileStream)
        {
            using (excelFileStream)
            {
                HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
                if (workbook.NumberOfSheets > 0)
                {
                    ISheet sheet = workbook.GetSheetAt(0);
                    return sheet.PhysicalNumberOfRows > 0;

}
            }
            return false;
        }
        #endregion

#endregion

}

NPOI读取Excel表格类的更多相关文章

  1. 使用NPOI读取Excel表格内容并进行修改

    前言 网上使用NPOI读取Excel文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的. 参考博文 http://www.cnblogs.com/restran/p/38894 ...

  2. NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理

    NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...

  3. 【第二篇】.NET用NPOI读取Excel表格并在页面预览

    博主用的是npoi2.0.1,支持.xls也支持.xlsx 直接上代码吧. <table class="table table-bordered table-striped" ...

  4. .NET Core 使用NPOI读取Excel返回泛型List集合

    我是一名 ASP.NET 程序员,专注于 B/S 项目开发.累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html 网上有很多关于npoi ...

  5. C# 读取Excel表格内容,以及NPOI的使用

    在实际的开发中,我们可能需要读写word或者Excel的内容,在我开发的项目中,需要读取Excel的内容,并将相对应的内容存储到数据库中,这里简单跟大家分享一下,希望能够帮助一些人. 我相信在读写wo ...

  6. 使用NPOI读取Excel数据到DataTable

    如今XML文件的存储格式大行其道,可是也不是适用于全部情况,非常多单位的数据交换还是使用Excel的形式.这就使得我们须要读取Excel内的数据.载入到程序中进行处理.可是如何有效率的读取,如何使程序 ...

  7. Java读取excel表格

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

  8. poi读取excel工具类

    package com.manage.utils; import ch.qos.logback.core.net.SyslogOutputStream; import com.google.gson. ...

  9. NPOI读取Excel遇到的坑

    NPOI是POI的.NET版本.POI是用Java写成的库,能帮助用户在没有安装Office环境下读取Office2003-2007文件.NPOI在.NET环境下使用,能读写Excel/Word文件. ...

随机推荐

  1. 12个有趣的C语言面试题

    摘要:12个C语言面试题,涉及指针.进程.运算.结构体.函数.内存,看看你能做出几个! 1.gets()函数 问:请找出下面代码里的问题: #include<stdio.h> int ma ...

  2. ThinkPad指纹验证在win7无法使用的解决方法

    原先本本装window7 64bit 专业版(正版),但用着用着觉得 很不爽 ,反应特慢.所以决定对本本来次大换血,换成windows server 2008 R2.最后在装指纹验证的时候,使用超级管 ...

  3. 从零开始学android开发- layout属性介绍

    android:id 为控件指定相应的ID android:text 指定控件当中显示的文字,需要注意的是,这里尽量使用strings.xml文件当中的字符串 android:gravity 指定Vi ...

  4. Android Camera

    Android调用系统api使用照相机功能,实现拍照获取图片以及从照相机库中获取指定图片的功能. 下面是演示样例代码: <?xml version="1.0" encodin ...

  5. C专家编程 总结

    1 类型转换 当执行算术运算时,操作数的类型如果不同,就会发生转换,数据类型一般朝着浮点精度高.长度更长的方向转换,整数型如果转换为signed不会丢失信息,就转换为signed,否则转换为unsig ...

  6. Date Format, 时间戳格式化

    // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...

  7. Programming Assignment 1: Percolation

    问题描述可以详见:http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 关于QuickFindUF的javadoc:h ...

  8. KMeans聚类 K值以及初始类簇中心点的选取 转

    本文主要基于Anand Rajaraman和Jeffrey David Ullman合著,王斌翻译的<大数据-互联网大规模数据挖掘与分布式处理>一书. KMeans算法是最常用的聚类算法, ...

  9. php技术概要汇总

    php搜索-> sphinx     coreseek : 中文分词.中文搜索     samba  :把linux服务器端目录映射的本地. 视频截图插件.音频视频转换(ffmpeg): 1)w ...

  10. Helpers\GeoCode

    Helpers\GeoCode This function connects to google maps and retrieves the lat/lon of the address provi ...