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. Using AngularJS with .NET MVC 5

    This tip shows the use of AngularJS with .NET MVC5 application. Here is a simple step-by-step exampl ...

  2. 也用 Log4Net 之将日志记录到数据库的后台实现 (二)

    也用 Log4Net 之将日志记录到数据库的后台实现 (二)  大家下午好,昨天讲了配置,今天我们讲讲后台实现,在完成了后台实现后,我们才能真正意义上的解决把自定义属性字段值录入到数据库中. 在开写之 ...

  3. 转载:C++ 虚函数表解析

    目录(?)[+]   转载:http://blog.csdn.net/haoel/article/details/1948051# 前言 C++中 的虚函数的作用主要是实现了多态的机制.关于多态,简而 ...

  4. POJ3279 Fliptile 枚举+简单搜索

    题意:一个矩阵,每个点1或0,然后每次翻一个点,它周围上下左右(包括自己)1->0,0->1,问最少翻几次可以矩阵全是0,忽略题目说的字典序 分析:枚举第一行所有的情况,然后下面几行也随之 ...

  5. 线性存储结构-Stack

    Stack继承于Vector,是一个模拟堆栈结构的集合类.当然也属于顺序存储结构.这里注意Android在com.android.layoutlib.bridge.impl包中也有一个Stack的实现 ...

  6. IE兼容性问题解决方案3--css中的overflow

    overflow:hidden:IE8下没效果? width:100%;IE6.7.8下必须有宽带,而且不能是auto: weight:auto; overflow-x:scroll; overflo ...

  7. MFC消息映射机制

    1.MFC应用框架主要类之间的关系 MFC自动生成的框架中重要的类有:C-App.CMainFrame.C-Doc和C-View. 其他的类如CClassView.CFileView等都是在框架窗口( ...

  8. 初涉C#防止黑客攻击站短

    一.同一个IP如果在一分钟内连续发送5个站短可以认为是不正确的,原因有2方面: 1.发站短的页面是有点击按钮,点击按钮后马上按钮会变为不可点击,所以在前端要防止点击一次触发多次的情况 2.发送短信的U ...

  9. SSDT Hook结构

    目录 SSDT Hook效果图 SSDT简介 SSDT结构 SSDT HOOK原理 Hook前准备 如何获得SSDT中函数的地址呢 SSDT Hook流程 SSDT Hook实现进程保护 Ring3与 ...

  10. HW6.7

    public class Solution { public static void main(String[] args) { int[] count = new int[10]; int numb ...