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 = ; //行高
ICell cell = row.CreateCell(); //创建第一列
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();
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();
//设置行高
titleRow.HeightInPoints = ;
//设置Title
titleRow.CreateCell().SetCellValue(strHeaderText);
//设置样式
titleRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Title);
//合并单元格
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
//设置边框
sheet.SetEnclosedBorderOfRegion(new NPOI.SS.Util.CellRangeAddress(, table.Rows.Count + , , ), CellBorderType.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index); //创建描述行
IRow descRow = sheet.CreateRow();
//设置行高
descRow.HeightInPoints = ;
//设置Title
descRow.CreateCell().SetCellValue(strDescText);
//设置样式
descRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Desc);
//合并单元格
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
sheet.SetEnclosedBorderOfRegion(new NPOI.SS.Util.CellRangeAddress(, , , ), CellBorderType.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index); IRow headerRow = sheet.CreateRow();
//设置行高
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue("序号");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("日期");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("时间");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("事件");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("媒体");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("研判");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().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().SetCellValue("责任单位");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("落实部门");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("处置");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("话题");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); headerRow.CreateCell().SetCellValue("地址");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , ));
headerRow.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); IRow headerRow2 = sheet.CreateRow();
headerRow2.HeightInPoints = ;
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("标题");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("摘要");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("名称");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("风险等级");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("调查落实");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("恢复引导");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("类别");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell().SetCellValue("关键词一");
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2);
headerRow2.CreateCell();
headerRow2.GetCell().CellStyle = CellStyle(workbook, CellStyleEnum.Head2); sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * ); // 行号
int rowIndex = ; foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
//dataRow.HeightInPoints = 70;//行高 int[] arrLenght = new int[];
arrLenght[] = row["SContent"].ToString().Length;
arrLenght[] = row["STitle"].ToString().Length;
arrLenght[] = row["SUrl"].ToString().Length; if (arrLenght[] > arrLenght[])
{
if (arrLenght[] > arrLenght[])
{
//arrLenght[0] 最大
dataRow.HeightInPoints = arrLenght[] + ;
}
else
{
//arrLenght[2] 最大
dataRow.HeightInPoints = arrLenght[] + ;
}
}
else if (arrLenght[] > arrLenght[])
{
//arrLenght[1] 最大
dataRow.HeightInPoints = arrLenght[] + ;
}
else
{
//arrLenght[2] 最大
dataRow.HeightInPoints = arrLenght[] + ;
} dataRow.CreateCell(, CellType.STRING).SetCellValue(rowIndex - );
dataRow.CreateCell(, CellType.STRING).SetCellValue(Convert.ToDateTime(row["SPostTime"]).ToString("MM.dd"));
dataRow.CreateCell(, CellType.STRING).SetCellValue(Convert.ToDateTime(row["SPostTime"]).ToString("HH:mm"));
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["STitle"].ToString());
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SContent"].ToString());
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SMedia"].ToString());
if (row["SRank"].ToString() == "")
{
dataRow.CreateCell(, CellType.STRING).SetCellValue("");
}
else
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(_SGSentimentBLL.RankTitle(Convert.ToInt32(row["SRank"])));
} if (!String.IsNullOrEmpty(row["SZone"].ToString()))
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SZone"].ToString().Substring(, ) + "公司");
}
else
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SZone"].ToString());
}
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SAdvanceDeptName"].ToString());
dataRow.CreateCell(, CellType.STRING).SetCellValue("");
dataRow.CreateCell(, CellType.STRING).SetCellValue("");
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["TypeName"].ToString());
dataRow.CreateCell(, 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 > )
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SUrl"].ToString().Substring());
}
else
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SUrl"].ToString());
}
}
else
{
dataRow.CreateCell(, CellType.STRING).SetCellValue(row["SUrl"].ToString());
} ICellStyle cellStyle = CellStyle(workbook, CellStyleEnum.Content2);
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle;
dataRow.GetCell().CellStyle = cellStyle; rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = ;
}
}
}
return ms;
}

    

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

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

    1.首先到网上下载"NPOI.DLL".引用. 2.新建一个操作类"ExcelHelper.cs": using System.Collections.Gene ...

  2. C#开发之基于NPOI的操作Excel开发体验

    最近遇到一个数据导入的需求,语言是.net framework 4.7的C#.但是,这次主要探讨NPOI的体验,原则就是向前兼容.所以采用.xls的支持.网上的资料,我稍微整合了一些. #1 单元格下 ...

  3. NPOI简单操作excel

    本文仅当是个记录文件,仅供初学者参考. 首先得using几个npoi的空间名如下: using NPOI.HSSF.UserModel;using NPOI.HSSF.Util;using NPOI. ...

  4. NPOI读取操作excel

    .读取using (FileStream stream = new FileStream(@"c:\客户资料.xls", FileMode.Open, FileAccess.Rea ...

  5. C#语言-NPOI.dll导入Excel功能的实现

    前言:刚工作那会,公司有一套完善的MVC框架体系,每当有导入EXCEL功能要实现的时候,都会借用框架里自带的导入方法,一般三下五除二就完成了,快是快,可总是稀里糊涂的,心里很没有底.前几天,在另一个原 ...

  6. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  7. C#通过NPOI操作Excel

    参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...

  8. NPOI操作EXCEL(六)——矩阵类表头EXCEL模板的解析

    哈哈~~~很高兴还活着.总算加班加点的把最后一类EXCEL模板的解析做完了... 前面几篇文章介绍了博主最近项目中对于复杂excel表头的解析,写得不好,感谢园友们的支持~~~ 今天再简单讲诉一下另一 ...

  9. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

随机推荐

  1. Asp.net MVC 4 异步方法

    今天我们来看一下,同样功能在 Asp.net MVC 4 下的实现,基于.net framework 4.5 下的async支持,让我们的代码更加简单,看下面片断代码名叫Index的Action方法: ...

  2. NetCat简介与使用方法

    精品学习网考试频道小编应广大考生的需要,特为参加考试的考生策划了“NetCat简介与使用方法”专题等有关资料,供考生参考! 在入侵中它是最经典的工具之一 ,NetCat被所有的网络安全爱好者和研究者称 ...

  3. HDU 5965 Gym Class 贪心+toposort

    分析:就是给一些拓补关系,然后求最大分数,所以贪心,大的越靠前越好,小的越靠后越好 剩下的就是toposort,当然由于贪心,所以使用优先队列 #include <iostream> #i ...

  4. Flume 与Kafka区别

    今天开会讨论日志处理为什么要同时使用Flume和Kafka,是否可以只用Kafka 不使用Flume?当时想到的就只用Flume的接口多,不管是输入接口(socket 和 文件)以及输出接口(Kafk ...

  5. SMG12232ZK标准字符点阵型液晶显示模块的演示程序[C51编程语言][MCS51并行接口方式]

    //SMG12232ZK标准字符点阵型液晶显示模块的演示程序[C51编程语言][MCS51并行接口方式] //应用产品: SMG12232ZK标准中文字符点阵型液晶显示模块 // 本演示程序适用于SM ...

  6. STM32软件仿真的一个注意点

    最近才做的板子由于自己的粗心把串口线搞反了,还好只有两条,飞线解决,而且现在还只是样板,但是还是应该引以为戒,以后做硬件一定要谨慎. 今天同事出差把CAN分析仪拿走了,本来在开发板上调试好的程序不知为 ...

  7. Keil: warning: A1581W: Added 2 bytes of padding at address

    KEIL MDK编译警告:   warning: A1581W: Added 2 bytes of padding at address xxx 原因: 在Keil 里写汇编代码时如果代码尺寸不对齐, ...

  8. iOS---RunLoop深度剖析

    RunLoop 前言 RunLoop是iOS/OS开发中比较基础的一个概念,在苹果开发中用在事件处理,延迟加载,屏幕刷新等功能的处理,其实抛开语言,RunLoop是一个的架构模式,也就是RunLoop ...

  9. SpringMVC(二)

    今天在完成的工作的前提下,最终在睡觉前将SpringMVC和Mybatis整合了~~~ 其实就是按照从网上(参考http://www.toutiao.com/a6332703083554324737/ ...

  10. html标签应用

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...