C# 之 用NPOI类库操作Excel

1、需引用以下命名空间:

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

2、接下来在内存中生成一个Excel文件,代码如下:

 HSSFWorkbook book = new HSSFWorkbook();
 ISheet sheet = book.CreateSheet("Sheet1");

3、然后在新创建的sheet里面,创建我们的行和列,代码如下:

IRow row = sheet.CreateRow(index); //index代表多少行
row.HeightInPoints = 35; //行高
ICell cell = row.CreateCell(0); //创建第一列
cell.SetCellValue("设置单元格的值"); //设置单元格的值

4、设置单元格的样式已经字体大小,边框,以及合并单元格

(1).创建单元格字体的样式及大小

        /// <summary>
        /// 获取字体样式
        /// </summary>
        /// <param name="hssfworkbook">Excel操作类</param>
        /// <param name="fontname">字体名</param>
        /// <param name="fontcolor">字体颜色</param>
        /// <param name="fontsize">字体大小</param>
        /// <returns></returns>
        public static IFont GetFontStyle(HSSFWorkbook hssfworkbook, string fontfamily, HSSFColor fontcolor, int fontsize)
        {
            IFont font1 = hssfworkbook.CreateFont();
            if (string.IsNullOrEmpty(fontfamily))
            {
                font1.FontName = fontfamily;
            }
            if (fontcolor != null)
            {
                font1.Color = fontcolor.GetIndex();
            }
            font1.IsItalic = true;
            font1.FontHeightInPoints = (short)fontsize;
            return font1;
        }

(2).设置单元格内显示数据的格式

ICell cell = row.CreateCell(1);
ICellStyle cellStyleNum = Excel.GetICellStyle(book);
IDataFormat formatNum = book.CreateDataFormat();
cellStyleNum.DataFormat = formatNum.GetFormat("0.00E+00");//设置单元格的格式为科学计数法cell.CellStyle = cellStyleNum;

(3).创建单元格的边框,背景颜色,以及对齐方式

        /// <summary>
        /// 获取单元格样式
        /// </summary>
        /// <param name="hssfworkbook">Excel操作类</param>
        /// <param name="font">单元格字体</param>
        /// <param name="fillForegroundColor">图案的颜色</param>
        /// <param name="fillPattern">图案样式</param>
        /// <param name="fillBackgroundColor">单元格背景</param>
        /// <param name="ha">垂直对齐方式</param>
        /// <param name="va">垂直对齐方式</param>
        /// <returns></returns>
        public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, IFont font, HSSFColor fillForegroundColor, FillPatternType fillPattern,      HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va)
        {
            ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
            cellstyle.FillPattern = fillPattern;
            cellstyle.Alignment = ha;
            cellstyle.VerticalAlignment = va;
            if (fillForegroundColor != null)
            {
                cellstyle.FillForegroundColor = fillForegroundColor.GetIndex();
            }
            if (fillBackgroundColor != null)
            {
                cellstyle.FillBackgroundColor = fillBackgroundColor.GetIndex();
            }
            if (font != null)
            {
                cellstyle.SetFont(font);
            }
            //有边框
            cellstyle.BorderBottom = CellBorderType.THIN;
            cellstyle.BorderLeft = CellBorderType.THIN;
            cellstyle.BorderRight = CellBorderType.THIN;
            cellstyle.BorderTop = CellBorderType.THIN;
            return cellstyle;
        }

(4).合并单元格 

        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="sheet">要合并单元格所在的sheet</param>
        /// <param name="rowstart">开始行的索引</param>
        /// <param name="rowend">结束行的索引</param>
        /// <param name="colstart">开始列的索引</param>
        /// <param name="colend">结束列的索引</param>
        public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
        {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
            sheet.AddMergedRegion(cellRangeAddress);
        }

5、将Excel文件输出

FileStream stream = File.OpenWrite(@"F:/test.xls"); ;
book.Write(stream);
stream.Close();

6、完整示例:

public MemoryStream RenderToExcelZBNew(DataTable table, string strHeaderText, string strDescText)
    {
        MemoryStream ms = new MemoryStream();

        using (table)
        {
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet())
                {

                    //创建标题行
                    IRow titleRow = sheet.CreateRow(0);
                    //设置行高
                    titleRow.HeightInPoints = 45;
                    //设置Title
                    titleRow.CreateCell(0).SetCellValue(strHeaderText);
                    //设置样式
                    titleRow.GetCell(0).CellStyle = CellStyle(workbook, CellStyleEnum.Title);
                    //合并单元格
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 13));
                    //设置边框
                    sheet.SetEnclosedBorderOfRegion(new NPOI.SS.Util.CellRangeAddress(0, table.Rows.Count + 3, 0, 13), CellBorderType.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index);

                    //创建描述行
                    IRow descRow = sheet.CreateRow(1);
                    //设置行高
                    descRow.HeightInPoints = 50;
                    //设置Title
                    descRow.CreateCell(0).SetCellValue(strDescText);
                    //设置样式
                    descRow.GetCell(0).CellStyle = CellStyle(workbook, CellStyleEnum.Desc);
                    //合并单元格
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 13));
                    sheet.SetEnclosedBorderOfRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 13), CellBorderType.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index);

                    IRow headerRow = sheet.CreateRow(2);
                    //设置行高
                    headerRow.HeightInPoints = 23;
                    headerRow.CreateCell(0).SetCellValue("序号");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 0, 0));
                    headerRow.GetCell(0).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(1).SetCellValue("日期");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 1, 1));
                    headerRow.GetCell(1).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(2).SetCellValue("时间");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 2, 2));
                    headerRow.GetCell(2).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(3).SetCellValue("事件");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 3, 4));
                    headerRow.GetCell(3).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(5).SetCellValue("媒体");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 5, 5));
                    headerRow.GetCell(5).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(6).SetCellValue("研判");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 6, 6));
                    headerRow.GetCell(6).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    //headerRow.CreateCell(7).SetCellValue("风险等级");
                    //sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 7, 7));
                    //headerRow.GetCell(7).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(7).SetCellValue("责任单位");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 7, 7));
                    headerRow.GetCell(7).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(8).SetCellValue("落实部门");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 8, 8));
                    headerRow.GetCell(8).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(9).SetCellValue("处置");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 9, 10));
                    headerRow.GetCell(9).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(11).SetCellValue("话题");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 11, 12));
                    headerRow.GetCell(11).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    headerRow.CreateCell(13).SetCellValue("地址");
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 3, 13, 13));
                    headerRow.GetCell(13).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    IRow headerRow2 = sheet.CreateRow(3);
                    headerRow2.HeightInPoints = 25;
                    headerRow2.CreateCell(0);
                    headerRow2.GetCell(0).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(1);
                    headerRow2.GetCell(1).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(2);
                    headerRow2.GetCell(2).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(7);
                    headerRow2.GetCell(7).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(8);
                    headerRow2.GetCell(8).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(9);
                    headerRow2.GetCell(9).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(3).SetCellValue("标题");
                    headerRow2.GetCell(3).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(4).SetCellValue("摘要");
                    headerRow2.GetCell(4).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(5).SetCellValue("名称");
                    headerRow2.GetCell(5).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(6).SetCellValue("风险等级");
                    headerRow2.GetCell(6).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(9).SetCellValue("调查落实");
                    headerRow2.GetCell(9).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(10).SetCellValue("恢复引导");
                    headerRow2.GetCell(10).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(11).SetCellValue("类别");
                    headerRow2.GetCell(11).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(12).SetCellValue("关键词一");
                    headerRow2.GetCell(12).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
                    headerRow2.CreateCell(13);
                    headerRow2.GetCell(13).CellStyle = CellStyle(workbook, CellStyleEnum.Head2);

                    sheet.SetColumnWidth(0, 4 * 256);
                    sheet.SetColumnWidth(1, 6 * 256);
                    sheet.SetColumnWidth(2, 6 * 256);
                    sheet.SetColumnWidth(3, 25 * 256);
                    sheet.SetColumnWidth(4, 25 * 256);
                    sheet.SetColumnWidth(5, 5 * 256);
                    sheet.SetColumnWidth(6, 5 * 256);
                    sheet.SetColumnWidth(7, 5 * 256);
                    sheet.SetColumnWidth(8, 5 * 256);
                    sheet.SetColumnWidth(9, 18 * 256);
                    sheet.SetColumnWidth(10, 18 * 256);
                    sheet.SetColumnWidth(11, 6 * 256);
                    sheet.SetColumnWidth(12, 6 * 256);
                    sheet.SetColumnWidth(13, 18 * 256);

                    // 行号
                    int rowIndex = 4;

                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        //dataRow.HeightInPoints = 70;//行高

                        int[] arrLenght = new int[3];
                        arrLenght[0] = row["SContent"].ToString().Length;
                        arrLenght[1] = row["STitle"].ToString().Length;
                        arrLenght[2] = row["SUrl"].ToString().Length;

                        if (arrLenght[0] > arrLenght[1])
                        {
                            if (arrLenght[0] > arrLenght[2])
                            {
                                //arrLenght[0] 最大
                                dataRow.HeightInPoints = arrLenght[0] + 15;
                            }
                            else
                            {
                                //arrLenght[2] 最大
                                dataRow.HeightInPoints = arrLenght[2] + 10;
                            }
                        }
                        else if (arrLenght[1] > arrLenght[2])
                        {
                            //arrLenght[1] 最大
                            dataRow.HeightInPoints = arrLenght[1] + 15;
                        }
                        else
                        {
                            //arrLenght[2] 最大
                            dataRow.HeightInPoints = arrLenght[2] + 10;
                        }

                        dataRow.CreateCell(0, CellType.STRING).SetCellValue(rowIndex - 3);
                        dataRow.CreateCell(1, CellType.STRING).SetCellValue(Convert.ToDateTime(row["SPostTime"]).ToString("MM.dd"));
                        dataRow.CreateCell(2, CellType.STRING).SetCellValue(Convert.ToDateTime(row["SPostTime"]).ToString("HH:mm"));
                        dataRow.CreateCell(3, CellType.STRING).SetCellValue(row["STitle"].ToString());
                        dataRow.CreateCell(4, CellType.STRING).SetCellValue(row["SContent"].ToString());
                        dataRow.CreateCell(5, CellType.STRING).SetCellValue(row["SMedia"].ToString());
                        if (row["SRank"].ToString() == "0")
                        {
                            dataRow.CreateCell(6, CellType.STRING).SetCellValue("");
                        }
                        else
                        {
                            dataRow.CreateCell(6, CellType.STRING).SetCellValue(_SGSentimentBLL.RankTitle(Convert.ToInt32(row["SRank"])));
                        }

                        if (!String.IsNullOrEmpty(row["SZone"].ToString()))
                        {
                            dataRow.CreateCell(7, CellType.STRING).SetCellValue(row["SZone"].ToString().Substring(0, 2) + "公司");
                        }
                        else
                        {
                            dataRow.CreateCell(7, CellType.STRING).SetCellValue(row["SZone"].ToString());
                        }
                        dataRow.CreateCell(8, CellType.STRING).SetCellValue(row["SAdvanceDeptName"].ToString());
                        dataRow.CreateCell(9, CellType.STRING).SetCellValue("");
                        dataRow.CreateCell(10, CellType.STRING).SetCellValue("");
                        dataRow.CreateCell(11, CellType.STRING).SetCellValue(row["TypeName"].ToString());
                        dataRow.CreateCell(12, CellType.STRING).SetCellValue(row["IssueName"].ToString());

                        if (row["SUrl"].ToString().Contains("http://t.qq.com/") || row["SUrl"].ToString().Contains("http://weibo.com/"))
                        {
                            if (row["SUrl"].ToString().Length > 50)
                            {
                                dataRow.CreateCell(13, CellType.STRING).SetCellValue(row["SUrl"].ToString().Substring(50));
                            }
                            else
                            {
                                dataRow.CreateCell(13, CellType.STRING).SetCellValue(row["SUrl"].ToString());
                            }
                        }
                        else
                        {
                            dataRow.CreateCell(13, CellType.STRING).SetCellValue(row["SUrl"].ToString());
                        }

                        ICellStyle cellStyle = CellStyle(workbook, CellStyleEnum.Content2);
                        dataRow.GetCell(0).CellStyle = cellStyle;
                        dataRow.GetCell(1).CellStyle = cellStyle;
                        dataRow.GetCell(2).CellStyle = cellStyle;
                        dataRow.GetCell(3).CellStyle = cellStyle;
                        dataRow.GetCell(4).CellStyle = cellStyle;
                        dataRow.GetCell(5).CellStyle = cellStyle;
                        dataRow.GetCell(6).CellStyle = cellStyle;
                        dataRow.GetCell(7).CellStyle = cellStyle;
                        dataRow.GetCell(8).CellStyle = cellStyle;
                        dataRow.GetCell(9).CellStyle = cellStyle;
                        dataRow.GetCell(10).CellStyle = cellStyle;
                        dataRow.GetCell(11).CellStyle = cellStyle;
                        dataRow.GetCell(12).CellStyle = cellStyle;
                        dataRow.GetCell(13).CellStyle = cellStyle;

                        rowIndex++;
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
            }
        }
        return ms;
    }

    

时间: 2024-10-05 23:46:35

C# 之 用NPOI类库操作Excel的相关文章

c# ASP.Net 使用开源免费类库操作Excel

主要找到以下类库: MyXls(http://sourceforge.net/projects/myxls/) Koogra(http://sourceforge.net/projects/koogra/) ExcelLibrary(http://code.google.com/p/excellibrary/) ExcelPackage(http://excelpackage.codeplex.com/) EPPlus(http://epplus.codeplex.com/) LinqToExc

asp.net(C#)之NPOI&amp;quot;操作Excel

1.首先到网上下载"NPOI.DLL".引用. 2.新建一个操作类"ExcelHelper.cs": using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; public class Exc

NPOI操作Excel 003:写入空Excel

对于NPOI操作Excel前面已经有了简单认识(http://blog.csdn.net/yysyangyangyangshan/article/details/42614209).继续来看如何将内容保存至Excel中.根据前面的经验NPOI操作Excel主要的几个对象分别是:workbook,sheet以及sheet内的row和cell.所以保存至Excel也是对这几个对象进行操作.当然我们平时使用Excel时不光要在单元格中保存内容,还要设置单元格的格式以及字体大小等,也就是格式和样式.这些

C#操作Excel之NPOI

最近要开发一个C#操作Excel的小工具,但是装上Office之后又是各种组件冲突. 后来发现了NPOI,觉得非常好用. 这里跟大家分享下, 官网:http://npoi.codeplex.com/downloads/get/872547 下面网站有教程:http://www.cnblogs.com/atao/archive/2009/11/15/1603528.html 教程里有的地方会报错,大家以官网为准.

NPOI操作excel——利用反射机制,NPOI读取excel数据准确映射到数据库字段

> 其实需求很明确,就是一大堆不一样的excel,每张excel对应数据库的一张表,我们需要提供用户上传excel,我们解析数据入库的功能实现. 那么,这就涉及到一个问题:我们可以读出excel的表头,但是怎么知道每个表头具体对应数据库里面的字段呢? 博主经过一段时间的思考与构思,想到一法:现在的情况是我们有excel表A,对应数据库表B,但是A与B具体属性字段的映射关系我们不知.那我们是不是可以有一个A到B的映射文件C呢? 我想,说到这,大家就很明了了... 第一步:为每张excel创建一个与

Net操作Excel(终极方法NPOI)

http://www.cnblogs.com/stone_w/archive/2012/08/02/2620528.html Net操作Excel(终极方法NPOI) 前言 Asp.net/C#操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等.NPOI是构建在POI 3.x版本之上的,它可以在

C#通过NPOI操作Excel

C#操作Excel的方法有很多种,常见的有微软官方的OLE Automation,Apache的POI等.这里介绍的是POI翻译成C#的NPOI. POI是Apache的通过Java操作Office的一个API,可以对Excel,Word,PPT等进行操作,十分的强大.然后就被翻译成C#版本的NPOI了,和log4j与log4net很相似. 好像在NPOI的.net4.0版本之前是不支持office2007及以上的XML格式的,但是最新的版本已经支持了.只需要下载并引用下面五个程序集就能使用了.

Npoi操作excel

转载地址:http://www.cnblogs.com/knowledgesea/archive/2012/11/16/2772547.html Npoi操作excel Npoi 简介 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.Npoi 下载地址:http://npoi.codeplex.com/releases/view/38113 3.Npoi 学习系列教程推荐:http://www.cnblogs.co

NPOI操作Excel 005:写入空Excel(Winform版)

前文写了一个BS版本号的导出Excel的样例(http://blog.csdn.net/yysyangyangyangshan/article/details/47904119).对于CS版在保存的地方有少许修改.直接看代码例如以下: private void button1_Click(object sender, EventArgs e) { //要保存的内容.此处用代码生成的内容,而在实际中能够是数据库读取的, //亦或是页面输入的内容 DataTable dt = new DataTab