第五空间

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

上周完成了一个报表小项目,使用开源组件NPOI作为主要组件。之所以采用第三方的开源组件而不使用COM或微软提供的API,原因就不多说了,大家懂的。

官方网站:http://npoi.codeplex.com/

http://www.cnblogs.com/tonyqus/archive/2009/03/16/1409966.html

在此分享NPOI的一个应用,利用Excel模板生成excel文件。这正是NPOI强于Myxls之处。

具体步骤如下:

一、准备数据

复制代码
USE[MonthReportDemo]
GO

/****** Object: Table [dbo].[TradeReport] Script Date: 04/15/2011 19:10:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IFNOTOBJECT_ID('[TradeReport]') ISNULL
DROPTABLE[TradeReport]
GO

CREATETABLE[dbo].[TradeReport](
[CurName][nvarchar](255) NULL,
[PlanValue][decimal](20, 2) NULL,
[MonthMoney][decimal](38, 0) NULL,
[YearMoney][decimal](38, 0) NULL,
[Year_Percent][int]NOTNULL,
[D_ID][int]identity(1,1),
constraint PK_TradeReport primarykeyclustered ([D_ID])
)

GO

insertinto TradeReport
select'绍兴润和购物中心有限公司',30000.00,3400,10000,0
unionallselect'新农都实业有限公司',0,3000,6000,0
unionallselect'浙江农发市政园林工程有限公司',6000.00,300,2340,0

select*from TradeReport
复制代码

 

二、新建一个项目,结构如下:

邀月工作室

模板文件如下:

三、预览结果:

邀月工作室

四、修正模板

重新生成:

邀月工作室

循环每个Cell,如果为0,则置为空

复制代码
#region Clear "0" 
System.Collections.IEnumerator rows 
= sheet.GetRowEnumerator(); 

int cellCount = headerRow.LastCellNum; 

for (int i = (sheet.FirstRowNum +1); i <= sheet.LastRowNum; i++) 
{ 
HSSFRow row 
= sheet.GetRow(i); 
if (row !=null) 
{ 
for (int j = row.FirstCellNum; j < cellCount; j++) 
{ 
HSSFCell c 
= row.GetCell(j); 
if (c !=null) 
{ 
switch (c.CellType) 
{ 
case HSSFCellType.NUMERIC: 
if (c.NumericCellValue ==0) 
{ 
c.SetCellType(HSSFCellType.STRING); 
c.SetCellValue(
string.Empty); 
} 
break; 
case HSSFCellType.BLANK: 

case HSSFCellType.STRING: 
if (c.StringCellValue =="0") 
{ c.SetCellValue(
string.Empty); } 
break; 

} 
} 
} 

} 

} 
#endregion
复制代码

 

邀月工作室

其实NPOI在实际项目中可以生成更加复杂的图表,如下图:

简单示例代码下载: 
下载二

下载一

 

转自:http://www.cnblogs.com/downmoon/archive/2011/04/16/2017603.html

 

posted on 2013-04-13 12:50  LearnerYQY  阅读(2219)  评论(0编辑  收藏  举报