NPOI Excel导出数据信息

1、这里引用的是   NPOI1.2.5.0版本。

2、导入命名空间

using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

3、新建一个导出类,直接将代码复制过去即可使用。

#region 通过NPOI组件导出EXCEL
        private static HSSFWorkbook hssfworkbook;

public class CommentModel
        {
            public int rowIndex;
            public int columnIndex;
            public string commentText;

public CommentModel(int row, int column, string text)
            {
                this.rowIndex = row;
                this.columnIndex = column;
                this.commentText = text;
            }
        }

public static void NpoiToExcel(DataTable dt)
        {
            NpoiToExcel(dt, null, null, null);
        }

public static void NpoiToExcel(DataTable dt, List<int> columnsHiddenIndex, List<int> columnsEnableIndex, CommentModel commentModel)
        {
            string filename = string.Format("Excel{0}.xls", System.DateTime.Now.Ticks);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            HttpContext.Current.Response.Clear();
            InitializeWorkbook();
            GenerateData(dt, columnsHiddenIndex, columnsEnableIndex, commentModel);
            HttpContext.Current.Response.BinaryWrite(WriteToStream().GetBuffer());
            HttpContext.Current.Response.End();
        }

private static MemoryStream WriteToStream()
        {
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file;
        }

private static void GenerateData(DataTable dt, List<int> columnsHiddenIndex, List<int> columnsEnableIndex, CommentModel commentModel)
        {
            ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

sheet1.DefaultColumnWidth = 20;

IRow rowHeader = sheet1.CreateRow(0);

// 设置背景颜色为天蓝色
            ICellStyle headerCellStyle = hssfworkbook.CreateCellStyle();
            headerCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SKY_BLUE.index;
            headerCellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;

// 设置单元格字体
            IFont font = hssfworkbook.CreateFont();
            font.Boldweight = (short)FontBoldWeight.BOLD; // 粗体
            headerCellStyle.SetFont(font);

// 设置单元格边框
            headerCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
            headerCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            headerCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
            headerCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;

headerCellStyle.WrapText = true;

// 设置导出标题
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = rowHeader.CreateCell(i);
                cell.CellStyle = headerCellStyle;
                cell.SetCellType(CellType.STRING);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

// 添加批注
            if (commentModel != null)
            {
                IDrawing patr = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();
                HSSFComment comment = (HSSFComment)patr.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, commentModel.columnIndex + 1, commentModel.rowIndex + 1, commentModel.columnIndex + 3, commentModel.rowIndex + 6));
                HSSFRichTextString str = new HSSFRichTextString(commentModel.commentText);
                IFont fontComment = hssfworkbook.CreateFont();
                fontComment.FontName = ("Arial");
                fontComment.FontHeightInPoints = 10;
                fontComment.Boldweight = (short)FontBoldWeight.BOLD;
                str.ApplyFont(fontComment);
                comment.String = str;
                comment.Row = commentModel.rowIndex;
                comment.Column = commentModel.columnIndex;
            }

// 设置单元格边框
            ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;

// 设置导出内容
            for (int i = 1; i <= dt.Rows.Count; i++)
            {

IRow row = sheet1.CreateRow(i);

for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string cellContent = dt.Rows[i - 1][j].ToString();

// 判断字符串大小,最大长度为32767,超过必须截取,否则设置EXCEL单元格会报错
                    if (cellContent.Length > 32767)
                    {
                        cellContent = cellContent.Substring(0, 32767);
                      
                    }

ICell cell = row.CreateCell(j);
                    cell.CellStyle = cellStyle;
                    cell.SetCellType(CellType.STRING);
                    cell.SetCellValue(cellContent);
                }

row.Height = 20 * 20;
            }

if (columnsHiddenIndex != null)
            {
                for (int n = 0; n < columnsHiddenIndex.Count; n++)
                {
                    sheet1.SetColumnHidden(columnsHiddenIndex[n], true);
                }
            }

if (columnsEnableIndex != null)
            {
                DVConstraint dvconstraint = DVConstraint.CreateExplicitListConstraint(new string[] { "Y", "N" });

for (int m = 0; m < columnsEnableIndex.Count; m++)
                {
                    //所有序号都从零算起,第一行标题行除外,所以第一个参数是1,65535是一个Sheet的最大行数 
                    CellRangeAddressList rangeList = new CellRangeAddressList(1, dt.Rows.Count, columnsEnableIndex[m], columnsEnableIndex[m]);
                    HSSFDataValidation dataValidation = new HSSFDataValidation(rangeList, dvconstraint);
                    ((HSSFSheet)sheet1).AddValidationData(dataValidation);
                }
            }
        }

private static void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();

DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "博客";
            hssfworkbook.DocumentSummaryInformation = dsi;

SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "博客园 Export";
            hssfworkbook.SummaryInformation = si;
        }

/// <summary>
        /// 根据excel文件路径 创建datatable
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string strPath)
        {
            FileStream stream = new FileStream(strPath, FileMode.Open, FileAccess.Read);

DataTable dt = new DataTable();
            HSSFWorkbook workbook = new HSSFWorkbook(stream);

HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
            HSSFRow headrow = (HSSFRow)sheet.GetRow(0);
            HSSFCell cell;

for (int i = 0; i < headrow.LastCellNum; i++)
            {
                cell = (HSSFCell)headrow.GetCell(i);
                dt.Columns.Add(cell.ToString());

}

int herdrowNum = headrow.LastCellNum;

for (int i = 0; i < sheet.LastRowNum; i++)
            {
                HSSFRow row = (HSSFRow)sheet.GetRow(i + 1);
                if (row != null)
                {
                    DataRow datarow = dt.NewRow();
                    for (int j = row.FirstCellNum; j < row.LastCellNum && j < herdrowNum; j++)
                    {
                        datarow[j] = row.GetCell(j) == null ? string.Empty : row.GetCell(j).ToString();
                    }

dt.Rows.Add(datarow);
                }
            }
            return dt;

}

#endregion

4、导出excel时汉化列明。

DataTable dtExport = new DataTable();
           
            //汉化的表头
            dtExport.Columns.Add(Resources.ExportColumns.GUID/*ID*/, typeof(string));
            dtExport.Columns.Add(Resources.ExportColumns.TASK_ID/*任务号*/, typeof(string));
            dtExport.Columns.Add(Resources.ExportColumns.CONTENT/*内容*/, typeof(string));
            dtExport.Columns.Add(Resources.ExportColumns.CREATOR_DATE/*日期*/, typeof(string));
            dtExport.Columns.Add(Resources.ExportColumns.CREATOR_NAME/*创建人*/, typeof(string));
            dtExport.Columns.Add(Resources.ExportColumns.CREATOR_ID/*创建工号*/, typeof(string));
            
            int colNo = 0;
            foreach (DataRow dr in dt.Rows)
            {
                colNo = 0;
                DataRow drExport = dtExport.NewRow();
                drExport[colNo++] = Convert.ToString(dr["GUID"]);
                drExport[colNo++] = Convert.ToString(dr["TASK_ID"]);
                drExport[colNo++] = Convert.ToString(dr["CONTENT"]);
                drExport[colNo++] = Convert.ToString(dr["CREATOR_DATE"]);
                drExport[colNo++] = Convert.ToString(dr["CREATOR_ID"]);
                drExport[colNo++] = Convert.ToString(dr["CREATOR_NAME"]);
                dtExport.Rows.Add(drExport);
            }
            dtExport.AcceptChanges();

Export.NpoiToExcel(dtExport);

时间: 2024-12-28 01:16:18

NPOI Excel导出数据信息的相关文章

asp.net使用MVC4框架基于NPOI做导出数据到Excel表

NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本

NPOI导入导出数据

//导入数据 protected void btnImport_Click(object sender, EventArgs e) { //判断fileImport控件中是否有需要上传的文件 if (this.fileImport.HasFile) { //判断文件类型是否符合要求   if (Path.GetExtension(this.fileImport.FileName) != ".xls") { MessageTips("上传的文件类型不符合要求", Me

Excel向数据库插入数据和数据库向Excel导出数据

为了熟悉java里工作簿的相关知识点,所以找了"Excel向数据库插入数据和数据库向Excel导出数据"的功能来实现. 注意事项:1,mysql数据库: 2,需要导入的jar包有 jxl.jar,mysql-connector-java-5.1.22-bin.jar,ojdbc6.jar 代码如下: 一, 建立数据库名称 javaforexcel,建立表stu DROP TABLE IF EXISTS `stu`;CREATE TABLE `stu` (  `id` int(11) N

使用NPOI方法导出数据到excel表中

使用NPOI方法导出到excel可以大量提高导出速度!步骤如下: (1)使用NPOI首先要有NPOI开发包(网上直接搜资源有的) (2)解压后把下边两个文件拷贝到自己的项目下(在bin目录下 .net4.0 下的 NPOI.dll和NPOI.xml) 我的项目结构大致如下 使用的是DAL结构 我把NPOI工具集放到了UI层 (3)添加引用(以我的项目为例:在我项目的UI点击引用--游览--然后找到刚才拷贝的两个文件 即可) (4)编写代码: 我的是一个点击事件 "导出" 前提条件就不说

excel表格数据信息传递老出错,还有没有更好用数据处理工具?

无论是外企.民企,还是事业单位,使用EXCEL进行办公是司空见惯的.EXCEL.WORD等办公软件带领办公从纸质化办公迈入无纸化办公时代,极大提高了办公的效率,保护了环境. 在互联网时代,我们越来越追求生活和工作的便利性,各行各业的劳作者也在思考,有什么软件可以替代EXCEL.WORD等办公软件,减少机械化的操作,让办公变得更加高效呢? 带着这样的思考,轻流应运而生,给各行各业带来了福音,让数据信息的传递更加方便快捷,减少了不必要的麻烦. 遇见TA前,用EXCEL办公 在没有接触到轻流前,数据收

ASP.NET Excel导出数据

protected void LinkButton1_Click(object sender, EventArgs e) { string strsql = " 1=1 "; int type = Convert.ToInt32(droptype.SelectedValue); string zyzids = String.Empty; if (type != 0) { List<zyz_zyztype> ztlist = zyz_zyztypeBLL.GetModelLi

thinkphp5中使用excel导出数据表格(包涵图片)

首先使用composer require phpoffice/phpexcel下载安装phpexcel包. 将包放入extend下面. 不附加图片的导出 /** * 导出excel(不带图片) * @param string $fileName [description] * @param [type] $headArr [description] * @param [type] $data [description] * @return [type] [description] */ publ

poI 以Excel导出数据

导入jar包,参考 http://zhuws.blog.51cto.com/11134439/1973698 2.步入正题,看代码 // 大致思路,先看本地文件存在不,如果不存在,把查询数据导出到Excel,然后再下载 代码有点乱 String filePath = request.getParameter("filePath"); filePath = new String( filePath.getBytes("iso-8859-1"), "UTF-8

C#调用excel导出数据时提示000208D5-0000-0000-C000-000000000046错误的解决办法

错误信息:000208D5-0000-0000-C000-000000000046 Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Application'. This operation failed because the QueryInterface call on the COM component for the interf