前言:最近项目里面有一些对excel操作的需求,博主想都没想,npoi呗,简单、开源、免费,大家都喜欢!确实,对于一些简单的excel导入、导出、合并单元格等,它都没啥太大的问题,但是这次的需求有两点是npoi搞不定的:
1、导入excel后, 需要切割excel的sheet页,然后每个sheet页单独生成一个pdf文件。
2、导出excel的时候, 项目里面需要将一些数据表格以图表的形式在excel里面展示。
找了一圈资料,对于excel生成pdf,网上的答案千篇一律:使用com组件的方式,通过调用服务器上面的office组件里面的东西去转。这种方式需要在服务器上面安装office,这倒是其次,最重要的是,权限的问题很头疼。博主已经按照这种方式实现了,调试的时候没问题,部署到iis上面之后又出了各种权限的问题,好不容易在一台服务器上面部署成功了,放到另一台服务器上面按照同样的方式部署,却还是提示[拒绝访问]。博主也是醉了。而对于excel生成图表,npoi暂时没找到实现方式,com组件的方式可以,但是实现起来略显复杂,并且这东西庞大、不太稳定,尤其是咱们大部分人个人电脑上面装的office都不是正版,使用起来也很麻烦。
基于此,经过一番努力,找到了这么一个 第三方组件spire.xls 。这两天体验了一把,使用起来还比较顺手,在此来简单介绍下这个组件的使用吧。
一、组件介绍
spire.xls是 e-iceblue 开发的一套基于企业级的专业office文档处理的组件之一,全称spire.office for .net。旗下有spire.doc,spire xls,spire.pdf,spire.barcode等多款专业组件,为各种office文档在程序处理上提供了很大的方便,官方为各种功能提供了大量的在线api,简化了使用组件的难度。组件使用时不需要本地office组件的支持。spire.office是一款企业级组件,它提供了收费版本和免费版本两种级别,一般来说,对于个人的应用,免费版本已足够用。比如对于上文博主遇到的问题,spire.xls组件就提供了很好的实现机制,如果你也遇到了npoi解决不了的问题,不妨试试这个。
[xls]是excel文件的后缀之一,顾名思义,spire.xls当然就是针对excel表格处理的组件喽,本篇,博主将结合上文遇到的问题来看看spire.xls组件的强大功能。
二、组件安装使用
对于组件的安装,在此还是提供两种方式:
1、官方下载安装
下载地址。官方下载的安装包是msi结尾的,安装时需要选择支持的vs版本等信息,软件的安装就不做过多说明,有兴趣的可以下载试试。
2、nuget安装
大家最喜欢的应该还是nuget方式吧,简单,方便,并且易于管理。博主也是不太喜欢为了一个组件而去单独下载一个安装包。
spire.xls也提供了nuget的方式,只需要搜索spire,选择免费版的组件即可:
安装完成后自动引用了需要的dll
三、组件功能介绍
关于excel的一些常用操作,比如取值、赋值、设置单元格样式等,这里就不做过多介绍,无论是com组件、npoi还是aspose,这些都是最基础的功能。下面就针对上文提出的几个问题着重说明下。
1、excel转pdf
(1)com组件实现思路回顾
关于excel转pdf的实现,网上找到的解决方案基本一样,大致代码如此:
/// <summary>
/// 把excel文件转换成pdf格式文件
/// </summary>
/// <param name="sourcepath">源文件路径</param>
/// <param name="targetpath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public bool xlsconverttopdf( string sourcepath, string targetpath)
{
logger.info( "开始转pdf" );
bool result = false ;
xlfixedformattype targettype = xlfixedformattype.xltypepdf;
object missing = type.missing;
microsoft.office.interop.excel.application application = null ;
microsoft.office.interop.excel.workbook workbook = null ;
try
{
application = new application();
application.interactive = false ;
object target = targetpath;
object type = targettype;
workbook = application.workbooks.open(sourcepath, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
application.interactive = true ;
workbook.exportasfixedformat(targettype, target, xlfixedformatquality.xlqualitystandard, true , false , missing, missing, missing, missing);
result = true ;
}
catch (exception ex)
{
logger.error( "excel转pdf异常,异常信息:" + ex.message + "。堆栈信息:" + ex.stacktrace);
result = false ;
}
finally
{
if (workbook != null )
{
workbook.close( true , missing, missing);
workbook = null ;
}
if (application != null )
{
application.quit();
application = null ;
}
gc.collect();
gc.waitforpendingfinalizers();
gc.collect();
gc.waitforpendingfinalizers();
}
return result;
}
这个方法需要依赖于本机上面的office com组件,如果你安装office的时候,没有安装com组件相关的dll,这个方法也是用不了的,并且还有一个最大的问题就是执行application.workbooks.open(sourcepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);这一个方法的时候需要当前用户有操作excel application这个组件的权限,尤其是部署到iis上面之后,需要配置一系列的权限,很是麻烦。
(2)spire.xls实现转换
通过上文,我们知道,spire.office提供了spire.xls和spire.pdf两个组件,那么他们之间的转换就简单了。我们还是模拟一个文件上传的功能。
前端有一个上传控件:
复制代码 代码如下:
<input type="file" name="txt_file" />
后台有一个接收上传文件的方法如下:
[httppost]
public jsonresult uploadfile()
{
var strres = string .empty;
var ofile = request.files[ "txt_file" ];
workbook book = new workbook();
book.loadfromstream(ofile.inputstream);
var strfullname = @"d:\data\upload\" + "first " + datetime.now.tostring(" yyyymmddhhmmss ") + " .pdf";
book.savetopdf(strfullname);
return json( new object { }, jsonrequestbehavior.allowget);
}
就这么简单的几句话即可实现将上传的excel转成pdf文件。根据源文件生成workbook对象,spire.xls提供了多种方式,我们最常用的两种方式如下:
// 根据文件路径生成workbook.
public void loadfromfile( string filename);
// 根据文件流生成workbook.
public void loadfromstream(stream stream);
2.1、最原始的转换
原始excel文件:
转换成pdf之后
2.2、不好看?加一个边框即可。
转换之后
2.3、自定义转换的pdf
有些情况下,我们excel里面有很多列,导致默认生成的pdf换行问题,这样将会导致pdf的可读性很差,这种情况,spire.xls为我们提供了自定义转换pdf的方式,比如可以指定pdf的页宽,页高,大小等等属性。
比如有如下excel文档需要转换成pdf文件:
如果按照常规的转换,生成的pdf的宽度不足以显示excel的所有列,于是转换出来的效果这样:
为了解决这种问题,组件为我们提供了如下方法:
[httppost]
public jsonresult uploadfile()
{
var strres = string .empty;
var ofile = request.files[ "txt_file" ];
workbook book = new workbook();
book.loadfromstream(ofile.inputstream);
var strfullname = @"d:\data\upload\" + "first " + datetime.now.tostring(" yyyymmddhhmmss ") + " .pdf";
pdfdocument pdfdocument = new pdfdocument();
pdfdocument.pagesettings.orientation = pdfpageorientation.landscape;
pdfdocument.pagesettings.width = 1800; //指定pdf的宽度
pdfdocument.pagesettings.height = 1000; //指定pdf的高度
pdfconvertersettings settings = new pdfconvertersettings();
settings.templatedocument = pdfdocument;
pdfconverter pdfconverter = new pdfconverter(book);
pdfdocument = pdfconverter.convert(settings);
pdfdocument.savetofile(strfullname);
return json( new object { }, jsonrequestbehavior.allowget);
}
这样就可以正常了,如果你的excel列更多,可以适当调整宽度和高度。得到的结果如下
还有更多强大的功能大家有兴趣可以慢慢探索,官方文档写得还算详细。
2.4、excel转其他类型
除了转为pdf,spire.xls还支持转换为其他类型,比如常见的xml、image、html等。如果大家有这方面的需求,可以深究一下。
2、excel生成图表
2.1、excel图表生成原理分析
通过下面一张图先来看看excel里面生成图表的原理
通过这张图我们可以看到,excel生成图表首先需要当前文档里面存在数据表格,然后选中相应的数据表格,最后选择生成的图表类型,excel应用会自动帮你生成相应的数据图表。
2.2、spire.xls生成简单图表
知道了上面excel生成图表的原理,我们再来看看spire.xls组件如何帮助我们解决生成图表的问题。关于生成图表,spire.xls组件提供了很多的选择,覆盖了excel里面各种自带的图表类型、统计方法等。下面先来看一个简单点的例子。
[httppost]
public jsonresult exportdata()
{
try
{
workbook book = new workbook();
worksheet sheet = book.worksheets[0];
var random = new random();
var icellcount = 1;
//1.设置表头
sheet.range[1, icellcount++].text = "部门名称" ;
sheet.range[1, icellcount++].text = "部门人数" ;
var lstdeptname = new list< string >() { "市场部" , "策划部" , "公关部" , "行政部" , "开发部" };
var a = 0;
//2.构造表数据
for (var i = 2; i < 7; i++)
{
icellcount = 1;
sheet.range[i, icellcount++].text = lstdeptname[a++];
sheet.range[i, icellcount++].numbervalue = random.next(1, 100); ;
}
//3.生成图表
setchart(sheet, excelcharttype.barclustered);var strfullname = @"d:\data\upload\" + "export " + datetime.now.tostring(" yyyymmddhhmmss ") + " .xlsx";
book.savetofile(strfullname, excelversion.version2010);
}
catch (exception ex)
{ }
return json( true , jsonrequestbehavior.allowget);
}
private void setchart(worksheet sheet, excelcharttype chartformat)
{
//1.设置sheet页的名称
sheet.name = "chart data" ;
sheet.gridlinesvisible = false ;
chart chart = sheet.charts.add();
//2.指定生成图表的区域
chart.datarange = sheet.range[ "a1:b6" ];
chart.seriesdatafromrange = false ;
//3.指定图表的所在位置
chart.leftcolumn = 5;
chart.toprow = 2;
chart.rightcolumn = 11;
chart.bottomrow = 29;
chart.charttype = chartformat;
//4.设置图表的名称以及x、y轴的名称
chart.charttitle = "部门信息" ;
chart.charttitlearea.isbold = true ;
chart.charttitlearea.size = 12;
chart.primarycategoryaxis.title = "部门" ;
chart.primarycategoryaxis.font.isbold = true ;
chart.primarycategoryaxis.titlearea.isbold = true ;
chart.primaryvalueaxis.title = "人数" ;
chart.primaryvalueaxis.hasmajorgridlines = false ;
chart.primaryvalueaxis.titlearea.textrotationangle = 90;
chart.primaryvalueaxis.minvalue = 0;
chart.primaryvalueaxis.titlearea.isbold = true ;
//5.设置图表的值
spire.xls.charts.chartserie cs = chart.series[0];
cs.categorylabels = sheet.range[ "a2:a6" ];
cs.values = sheet.range[ "b2:b6" ];
cs.dataformat.showactivevalue = true ;
chart.legend.position = legendpositiontype.top;
}
通过以上一段代码得到的excel内容如下:
代码释疑:关于上面的代码不难,但还是想做些简单的说明。
首先填充表格数据,spire.xls读写数据表格使用的是sheet.range[i, icellcount++].text这种方式。值得一提的是这里的行列索引都是从1开始的。range除了提供行列索引的方式,还提供了range["b1"].text这种方式去读取值。
通过上文excel生成图表原理我们知道,出了有数据表格,还得选中生成图表的区域,上述代码里面通过chart.datarange = sheet.range["a1:b6"];这一句去指定区域,和excel里面的操作方式保持一致。
通过chart.charttype = chartformat;来指定需要生成的图表类型,spire.xls里面通过一个枚举类型包含了各种图表类型。
除了上面的这些,组件还支持指定图表在文档中的位置、图表坐标的最大值最小值。并且能够通过
复制代码 代码如下:
spire.xls.charts.chartserie cs = chart.series[0];cs.categorylabels = sheet.range["a2:a6"];cs.values = sheet.range["b2:b6"];
这种方式去指定分类和值的区域,更加符合excel的操作习惯。当然,如无特殊,这些完全可以不用指定。
2.3、对两项或者多项进行统计
上面只是一个最简单的例子,如果要对多列进行统计呢?我们继续来看这个例子,我们将代码改成这样:
[httppost]
public jsonresult exportdata()
{
try
{
workbook book = new workbook();
worksheet sheet = book.worksheets[0];
var random = new random();
var icellcount = 1;
//1.设置表头
sheet.range[1, icellcount++].text = "部门名称" ;
sheet.range[1, icellcount++].text = "在职人数" ;
sheet.range[1, icellcount++].text = "离职人数" ;
var lstdeptname = new list< string >() { "市场部" , "策划部" , "公关部" , "行政部" , "开发部" };
var a = 0;
//2.构造表数据
for (var i = 2; i < 7; i++)
{
icellcount = 1;
sheet.range[i, icellcount++].text = lstdeptname[a++];
sheet.range[i, icellcount++].numbervalue = random.next(1, 100);
sheet.range[i, icellcount++].numbervalue = random.next(1, 100); ;
}
//3.生成图表
setchart(sheet, excelcharttype.barclustered);
var strfullname = @"d:\data\upload\" + "export " + datetime.now.tostring(" yyyymmddhhmmss ") + " .xlsx";
book.savetofile(strfullname, excelversion.version2010);
}
catch (exception ex){}
return json( true , jsonrequestbehavior.allowget);
}
private void setchart(worksheet sheet, excelcharttype chartformat)
{
//1.设置sheet页的名称
sheet.name = "chart data" ;
sheet.gridlinesvisible = false ;
chart chart = sheet.charts.add();
//2.指定生成图表的区域
chart.datarange = sheet.range[ "a1:c6" ];
chart.seriesdatafromrange = false ;
//3.指定图表的所在位置
chart.leftcolumn = 5;
chart.toprow = 2;
chart.rightcolumn = 11;
chart.bottomrow = 29;
chart.charttype = chartformat;
//4.设置图表的名称以及x、y轴的名称
chart.charttitle = "部门信息" ;
chart.charttitlearea.isbold = true ;
chart.charttitlearea.size = 12;
chart.primarycategoryaxis.title = "部门" ;
chart.primarycategoryaxis.font.isbold = true ;
chart.primarycategoryaxis.titlearea.isbold = true ;
chart.primaryvalueaxis.title = "人数" ;
chart.primaryvalueaxis.hasmajorgridlines = false ;
chart.primaryvalueaxis.titlearea.textrotationangle = 90;
chart.primaryvalueaxis.minvalue = 0;
chart.primaryvalueaxis.titlearea.isbold = true ;
//5.设置图表的值
spire.xls.charts.chartserie cs = chart.series[0];
cs.dataformat.showactivevalue = true ;
cs.dataformat.showbubble = true ;
chart.legend.position = legendpositiontype.top;
}
得到结果如下:
这里唯一的变化是数据区域,只要指定我们需要生成图表的区域是哪部分,excel会自动进行计算并生成图表。
2.4、各种类型的图表展示
上文说过,chart.charttype = chartformat;这一句可以设置图表的类型,在spire.xls里面定义了一系列的图表类型:
amespace spire.xls
{
// 摘要:
// chart types.
public enum excelcharttype
{
// 摘要:
// represents the column clustered chart type.
columnclustered = 0,
//
// 摘要:
// represents the stacked column chart type.
columnstacked = 1,
//
// 摘要:
// represents the 100% stacked column chart type.
column100percentstacked = 2,
//
// 摘要:
// represents the 3d clustered column chart type.
column3dclustered = 3,
//
// 摘要:
// represents the 3d stacked column chart type.
column3dstacked = 4,
//
// 摘要:
// represents the 3d 100% stacked column chart type.
column3d100percentstacked = 5,
//
// 摘要:
// represents the 3d column chart type.
column3d = 6,
//
// 摘要:
// represents the clustered bar chart type.
barclustered = 7,
//
// 摘要:
// represents the stacked bar chart type.
barstacked = 8,
//
// 摘要:
// represents the 100% stacked bar chart type.
bar100percentstacked = 9,
//
// 摘要:
// represents the 3d clustered bar chart type.
bar3dclustered = 10,
//
// 摘要:
// represents the 3d stacked bar chart type.
bar3dstacked = 11,
//
// 摘要:
// represents the 100% 3d stacked bar chart type.
bar3d100percentstacked = 12,
//
// 摘要:
// represents the line chart type.
line = 13,
//
// 摘要:
// represents the stacked line chart type.
linestacked = 14,
//
// 摘要:
// represents the 100% stacked line chart type.
line100percentstacked = 15,
//
// 摘要:
// represents the markers line chart type.
linemarkers = 16,
//
// 摘要:
// represents the stacked markers line chart type.
linemarkersstacked = 17,
//
// 摘要:
// represents the 100% stacked markers line chart type.
linemarkers100percentstacked = 18,
//
// 摘要:
// represents the 3d line chart type.
line3d = 19,
//
// 摘要:
// represents the pie chart type.
pie = 20,
//
// 摘要:
// represents the 3d pie chart type.
pie3d = 21,
//
// 摘要:
// represents the pie of pie chart type.
pieofpie = 22,
//
// 摘要:
// represents the exploded pie chart type.
pieexploded = 23,
//
// 摘要:
// represents the 3d exploded pie chart type.
pie3dexploded = 24,
//
// 摘要:
// represents the bar pie chart type.
piebar = 25,
//
// 摘要:
// represents the markers scatter chart type.
scattermarkers = 26,
//
// 摘要:
// represents the scattersmoothedlinemarkers chart type.
scattersmoothedlinemarkers = 27,
//
// 摘要:
// represents the scattersmoothedline chart type.
scattersmoothedline = 28,
//
// 摘要:
// represents the scatterlinemarkers chart type.
scatterlinemarkers = 29,
//
// 摘要:
// represents the scatterline chart type.
scatterline = 30,
//
// 摘要:
// represents the area chart type.
area = 31,
//
// 摘要:
// represents the areastacked chart type.
areastacked = 32,
//
// 摘要:
// represents the area100percentstacked chart type.
area100percentstacked = 33,
//
// 摘要:
// represents the area3d chart type.
area3d = 34,
//
// 摘要:
// represents the area3dstacked chart type.
area3dstacked = 35,
//
// 摘要:
// represents the area3d100percentstacked chart type.
area3d100percentstacked = 36,
//
// 摘要:
// represents the doughnut chart type.
doughnut = 37,
//
// 摘要:
// represents the doughnutexploded chart type.
doughnutexploded = 38,
//
// 摘要:
// represents the radar chart type.
radar = 39,
//
// 摘要:
// represents the radarmarkers chart type.
radarmarkers = 40,
//
// 摘要:
// represents the radarfilled chart type.
radarfilled = 41,
//
// 摘要:
// represents the surface3d chart type.
surface3d = 42,
//
// 摘要:
// represents the surface3dnocolor chart type.
surface3dnocolor = 43,
//
// 摘要:
// represents the surfacecontour chart type.
surfacecontour = 44,
//
// 摘要:
// represents the surfacecontournocolor chart type.
surfacecontournocolor = 45,
//
// 摘要:
// represents the bubble chart type.
bubble = 46,
//
// 摘要:
// represents the bubble3d chart type.
bubble3d = 47,
//
// 摘要:
// represents the stockhighlowclose chart type.
stockhighlowclose = 48,
//
// 摘要:
// represents the stockopenhighlowclose chart type.
stockopenhighlowclose = 49,
//
// 摘要:
// represents the stockvolumehighlowclose chart type.
stockvolumehighlowclose = 50,
//
// 摘要:
// represents the stockvolumeopenhighlowclose chart type.
stockvolumeopenhighlowclose = 51,
//
// 摘要:
// represents the cylinderclustered chart type.
cylinderclustered = 52,
//
// 摘要:
// represents the cylinderstacked chart type.
cylinderstacked = 53,
//
// 摘要:
// represents the cylinder100percentstacked chart type.
cylinder100percentstacked = 54,
//
// 摘要:
// represents the cylinderbarclustered chart type.
cylinderbarclustered = 55,
//
// 摘要:
// represents the cylinderbarstacked chart type.
cylinderbarstacked = 56,
//
// 摘要:
// represents the cylinderbar100percentstacked chart type.
cylinderbar100percentstacked = 57,
//
// 摘要:
// represents the cylinder3dclustered chart type.
cylinder3dclustered = 58,
//
// 摘要:
// represents the coneclustered chart type.
coneclustered = 59,
//
// 摘要:
// represents the conestacked chart type.
conestacked = 60,
//
// 摘要:
// represents the cone100percentstacked chart type.
cone100percentstacked = 61,
//
// 摘要:
// represents the conebarclustered chart type.
conebarclustered = 62,
//
// 摘要:
// represents the conebarstacked chart type.
conebarstacked = 63,
//
// 摘要:
// represents the conebar100percentstacked chart type.
conebar100percentstacked = 64,
//
// 摘要:
// represents the cone3dclustered chart type.
cone3dclustered = 65,
//
// 摘要:
// represents the pyramidclustered chart type.
pyramidclustered = 66,
//
// 摘要:
// represents the pyramidstacked chart type.
pyramidstacked = 67,
//
// 摘要:
// represents the pyramid100percentstacked chart type.
pyramid100percentstacked = 68,
//
// 摘要:
// represents the pyramidbarclustered chart type.
pyramidbarclustered = 69,
//
// 摘要:
// represents the pyramidbarstacked chart type.
pyramidbarstacked = 70,
//
// 摘要:
// represents the pyramidbar100percentstacked chart type.
pyramidbar100percentstacked = 71,
//
// 摘要:
// represents the pyramid3dclustered chart type.
pyramid3dclustered = 72,
//
// 摘要:
// represents the combinationchart chart types.
combinationchart = 73,
}
}
我们来看看一些比较常见的图表
2.4.1、饼状图
excelcharttype.pie
excelcharttype.pie3d
2.4.2、连线图
excelcharttype.line3d
excelcharttype.linestacked
2.4.3、区域图
2.4.4、雷达图
2.4.5、圆形柱状图
3、其他功能介绍
关于spire.xls的其他亮点功能,博主也还在研究,已经知道的一些常用功能比如(1)支持单元格合并、冻结、注释;(2)数据库方式的导入导出;(3)sheet页的复制、切割、显示、隐藏等;(4)页眉页脚的设置;(5)数据的分组、排序;(6)像excel插入图片,设置图片样式等。这些功能有些已经实现,有些还在研究,等以后有机会再发出来供大家参考。因为篇幅问题,这篇先到这里吧。
四、总结
以上简单总结了下spire.xls组件几个特色功能,很好的解决了博主遇到的问题,博主觉得在一定程度上,spire.xls组件能拟补npoi、com组件的部分不足。还有很多其他特色功能待以后整理之后连带测试demo一起发出。如果你也遇到一些其他组件解决不了的问题,不妨试试它,或许会带给你惊喜。当然,如果本文能够帮到你,还是希望园友们帮忙推荐,博主下次继续努力!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://HdhCmsTestcnblogs测试数据/landeanfen/p/5888973.html
dy("nrwz");
查看更多关于C#组件系列 你值得拥有的一款Excel处理神器Spire.XLS的详细内容...