NPOI导出Excel

时间:2022-02-06 02:29:49

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#region NPOI
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.Web;
using System.IO;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
#endregion
/*========================================================================================
 *
 *
 * 说  明:导入、导出Excel
 * 作  者:李朝强
 * 日  期:2015/03/28
 *
 *
 * =====================================================================================*/
namespace TiKu.Common.Office
{
    public class Excel
    {

#region ===============================================导出==================================
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="context">请求上下文</param>
        /// <param name="fileName">导出文件的名</param>
        /// <param name="stream">数据流</param>
        public void Export(HttpContext context,
                           string fileName,
                           MemoryStream stream)
        {
            if (context.Request.Browser.Browser == "IE")
                fileName = HttpUtility.UrlEncode(fileName);
            context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            context.Response.BinaryWrite(stream.ToArray());
        }

/// <summary>
        /// 导出
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="filename">导出的文件名</param>
        /// <param name="data">数据</param>
        public void Export(HttpContext context,
                           string filename,
                           string sheetName,
                           Hashtable hashColumnInfos,
                           DataTable data)
        {
            MemoryStream ms = null;
            try
            {
                ms = ReadToExcel(data,
                                 sheetName,
                                 hashColumnInfos);
                //执行导出
                Export(context, filename, ms);
            }
            catch (Exception ex) { throw ex; }
            finally
            {
                if (null != ms)
                {
                    ms.Close();
                    ms.Dispose();
                }
            }
        }

/// <summary>
        /// 从Repeat控件中,导出Excel
        /// </summary>
        /// <param name="RepList">控件</param>
        /// <param name="filename">文件名</param>
        /// <param name="sheetName">工作表</param>
        public void Export(Repeater RepList,
                           string filename,
                           string sheetName,
                           HttpContext context)
        {
            object data = RepList.DataSource;
            if (data is DataTable)
            {
                Export(context,
                       filename,
                       sheetName,
                       null,
                       (DataTable)data);
                return;
            }
            if (data is DataView)
            {
                return;
            }
            if (data is IList)
            {
                return;
            }
        }
        #endregion

#region ================================================数据流========================================
        /// <summary>
        /// 把DataTable对象,读取到内存流中
        /// </summary>
        /// <param name="data">DataTable对象</param>
        /// <param name="hashColumnInfos">(可选)列</param>
        /// <returns></returns>
        public MemoryStream ReadToExcel(DataTable data,
                                        string sheetName,
                                        Hashtable hashColumnInfos)
        {
            sheetName = string.IsNullOrEmpty(sheetName) ? string.Format("Sheet-{0:yyy/MM/dd}", DateTime.Now) : sheetName;
            //0>内存流
            MemoryStream ms = new MemoryStream();
            //1>创建工作薄
            IWorkbook __workbook = new HSSFWorkbook();
            //2>创建工作表
            ISheet __sheet = __workbook.CreateSheet(sheetName);

#region 单元格样式
            //单元格样式
            ICellStyle cellStyle = __workbook.CreateCellStyle();
            cellStyle.FillPattern = FillPattern.SolidForeground;
            cellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
            //设置字体
            IFont font = __workbook.CreateFont();
            font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
            cellStyle.SetFont(font);

cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
            #endregion

#region 3>创建表头
            //创建一行
            IRow __header = __sheet.CreateRow(0);
            if (null == hashColumnInfos)
            {
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    //创建单元格
                    ICell __cell = __header.CreateCell(i);
                    __cell.SetCellValue(data.Columns[i].ColumnName);
                    __sheet.SetColumnWidth(i, 20 * 256);
                    __cell.CellStyle = cellStyle;
                }
            }
            else
            {
                int j = 0;
                foreach (DictionaryEntry item in hashColumnInfos)
                {
                    //创建单元格
                    ICell __cell = __header.CreateCell(j);
                    __cell.SetCellValue(item.Value.ToString());
                    __sheet.SetColumnWidth(j, 20 * 256);
                    __cell.CellStyle = cellStyle;
                    ++j;
                }
            }
            #endregion

#region 4>创建数据行
            int c = 0;
            for (int k = 0; k < data.Rows.Count; k++)
            {
                IRow __dataRow = __sheet.CreateRow(k + 1);
                for (c = 0; c < data.Columns.Count; c++)
                {
                    ICell iCell = __dataRow.CreateCell(c);
                    iCell.SetCellValue(data.Rows[k][data.Columns[c].ColumnName].ToString());
                    c++;
                }
                c = 0;
            }
            #endregion

//5>最后,写入内存流
            __workbook.Write(ms);
            return ms;

}

/// <summary>
        /// 把IDataReader对象,读取到内存流中
        /// </summary>
        /// <param name="dataReader">IDataReader对象</param>
        /// <param name="sheetName">工作表名称</param>
        /// <param name="hashColumnInfos">列</param>
        /// <returns></returns>
        public MemoryStream ReadToExcel(IDataReader dataReader,
                                        string sheetName,
                                        Hashtable hashColumnInfos)
        {
            //0>内存流
            MemoryStream ms = new MemoryStream();
            //1>创建工作薄
            IWorkbook __workbook = new HSSFWorkbook();

//2>创建工作表
            ISheet __sheet = __workbook.CreateSheet(sheetName);

#region 3>表头
            IRow __header = __sheet.CreateRow(0);
            if (null == hashColumnInfos)
            {
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    ICell iHeaderCell = __header.CreateCell(i);
                    iHeaderCell.SetCellValue(dataReader.GetName(i));
                }
            }
            else
            {
                int j = 0;
                foreach (DictionaryEntry item in hashColumnInfos)
                {
                    //创建单元格
                    ICell __cell = __header.CreateCell(j);
                    __cell.SetCellValue(item.Value.ToString());
                    ++j;
                }
            }
            #endregion

#region 4>数据行
            int n = 1;
            while (dataReader.Read())
            {
                IRow __dataRow = __sheet.CreateRow(n);
                for (int c = 0; c < dataReader.FieldCount; c++)
                {
                    ICell iCell = __dataRow.CreateCell(c);
                    iCell.SetCellValue((dataReader.GetValue(c) ?? "").ToString());
                }
            }
            #endregion

//5>写入内存流
            __workbook.Write(ms);

return ms;
        }
        #endregion

}
}

NPOI导出Excel的更多相关文章

  1. NPOI导出Excel &lpar;C&num;&rpar; 踩坑 之--The maximum column width for an individual cell is 255 charaters

    /******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...

  2. Asp&period;Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  3. NPOI导出EXCEL 打印设置分页及打印标题

    在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置  sheet1.FitToPage = false; 而 ...

  4. &period;NET NPOI导出Excel详解

    NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...

  5. NPOI导出Excel(含有超过65335的处理情况)

    NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...

  6. &lbrack;转&rsqb;NPOI导出EXCEL 打印设置分页及打印标题

    本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...

  7. 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限

    大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...

  8. 用NPOI导出Excel

    用NPOI导出Excel public void ProcessRequest(HttpContext context) { context.Response.ContentType = " ...

  9. NPOI导出Excel示例

    摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...

  10. NPOI导出excel(带图片)

    近期项目中用到Excel导出功能,之前都是用普通的office组件导出的方法,今天尝试用下NPOI,故作此文以备日后查阅. 1.NPOI官网http://npoi.codeplex.com/,下载最新 ...

随机推荐

  1. Leetcode 99&colon; Recovery binary search tree 总算明白了算法&comma; 把代码写清楚&comma; 让错误无处可藏&period;

    想写点什么, 因为这道题花了我好几个小时, 在周日, 除了在球场上跑了二个小时, 就泡在这道题上面. read blogs: http://www.lifeincode.net/programming ...

  2. iOS 数据库持久化

    Java代码 -(void) addObserver{ //当程序进入后台时执行操作 UIApplication *app = [UIApplication sharedApplication]; [ ...

  3. 微软职位内部推荐-Senior Software Engineer-News

    微软近期Open的职位: News is a critical areas for integration of mobile and services, one of the top priorit ...

  4. C语言之scarf函数

    一 基本用法 scanf函数:接收用户的输入 语法: scanf("格式化控制符",地址列表); 例: int num; scanf("%d",&num ...

  5. js模拟点击事件实现代码

    js模拟点击事件实现代码 类型:转载 时间:2012-11-06 在实际的应用开发中,我们会常常用到JS的模事件,比如说点击事件,举个简单的例子,点击表单外的"提交"按钮来提交表单 ...

  6. c&num; 颜色RGB到HSB互相转换

    /// <summary> /// 色相,饱和度,亮度转换成rgb值 /// </summary> /// <returns></returns> pu ...

  7. &lbrack;Swift&rsqb;LeetCode812&period; 最大三角形面积 &vert; Largest Triangle Area

    You have a list of points in the plane. Return the area of the largest triangle that can be formed b ...

  8. 使用pip cmd安装包

    pip install matplotlib -i http://pypi.douban.com/simple --trusted-host pypi.douban.com,通过命令行安装的时候,指定 ...

  9. POJ - 2057 The Lost House(树形DP&plus;贪心)

    https://vjudge.net/problem/POJ-2057 题意 有一只蜗牛爬上某个树枝末睡着之后从树上掉下来,发现后面的"房子"却丢在了树上面,.现在这只蜗牛要求寻找 ...

  10. HDU5919 SequenceⅡ

    从后向前建主席树,以位置为下标建树,然后查询区间出现次数的第k/2大即可. 复杂度O(nlogn) #include<bits/stdc++.h> using namespace std; ...