这一节,我们将综合NPOI的常用功能(包括创建和填充单元格、合并单元格、设置单元格样式和利用公式),做一个工资单的实例。先看创建标题行的代码:


//写标题文本

HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

HSSFCell cellTitle = sheet1.CreateRow(0).CreateCell(0);

cellTitle.SetCellValue("XXX公司2009年10月工资单");

//设置标题行样式

HSSFCellStyle style = hssfworkbook.CreateCellStyle();

style.Alignment = HSSFCellStyle.ALIGN_CENTER;

HSSFFont font = hssfworkbook.CreateFont();

font.FontHeight = 20 * 20;

style.SetFont(font);

cellTitle.CellStyle = style;

//合并标题行

sheet1.AddMergedRegion(new Region(0, 0, 1, 6));

其中用到了我们前面讲的设置单元格样式和合并单元格等内容。接下来我们循环创建公司每个员工的工资单:


DataTable dt=GetData();

HSSFRow row;

HSSFCell cell;

HSSFCellStyle celStyle=getCellStyle();

HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();

HSSFClientAnchor anchor;

HSSFSimpleShape line;

int rowIndex;

for (int i = 0; i < dt.Rows.Count; i++)

{

    //表头数据

    rowIndex = 3 * (i + 1);

    row = sheet1.CreateRow(rowIndex);

    cell = row.CreateCell(0);

    cell.SetCellValue("姓名");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(1);

    cell.SetCellValue("基本工资");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(2);

    cell.SetCellValue("住房公积金");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(3);

    cell.SetCellValue("绩效奖金");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(4);

    cell.SetCellValue("社保扣款");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(5);

    cell.SetCellValue("代扣个税");

    cell.CellStyle = celStyle;

    cell = row.CreateCell(6);

    cell.SetCellValue("实发工资");

    cell.CellStyle = celStyle;

    DataRow dr = dt.Rows[i];

    //设置值和计算公式

    row = sheet1.CreateRow(rowIndex + 1);

    cell = row.CreateCell(0);

    cell.SetCellValue(dr["FName"].ToString());

    cell.CellStyle = celStyle;

    cell = row.CreateCell(1);

    cell.SetCellValue((double)dr["FBasicSalary"]);

    cell.CellStyle = celStyle;

    cell = row.CreateCell(2);

    cell.SetCellValue((double)dr["FAccumulationFund"]);

    cell.CellStyle = celStyle;

    cell = row.CreateCell(3);

    cell.SetCellValue((double)dr["FBonus"]);

    cell.CellStyle = celStyle;

    cell = row.CreateCell(4);

    cell.SetCellFormula(String.Format("$B{0}*0.08",rowIndex+2));

    cell.CellStyle = celStyle;

    cell = row.CreateCell(5);

    cell.SetCellFormula(String.Format("SUM($B{0}:$D{0})*0.1",rowIndex+2));

    cell.CellStyle = celStyle;

    cell = row.CreateCell(6);

    cell.SetCellFormula(String.Format("SUM($B{0}:$D{0})-SUM($E{0}:$F{0})",rowIndex+2));
    cell.CellStyle = celStyle;     //绘制分隔线
    sheet1.AddMergedRegion(new Region(rowIndex+2, 0, rowIndex+2, 6));
    anchor = new HSSFClientAnchor(0, 125, 1023, 125, 0, rowIndex + 2, 6, rowIndex + 2);
    line = patriarch.CreateSimpleShape(anchor);
    line.ShapeType = HSSFSimpleShape.OBJECT_TYPE_LINE;
    line.LineStyle = HSSFShape.LINESTYLE_DASHGEL; }

其中为了文件打印为单元格增加了黑色边框的样式(如果不设置边框样式,打印出来后是没有边框的)。另外,注意循环过程中excel中的行号随数据源中的行号变化处理。完整代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using System.Data;

namespace Payroll
{
    public class Program
    {
        static HSSFWorkbook hssfworkbook;

static void Main(string[] args)
        {
            InitializeWorkbook();

//写标题文本
            HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
            HSSFCell cellTitle = sheet1.CreateRow(0).CreateCell(0);
            cellTitle.SetCellValue("XXX公司2009年10月工资单");

//设置标题行样式
            HSSFCellStyle style = hssfworkbook.CreateCellStyle();
            style.Alignment = HSSFCellStyle.ALIGN_CENTER;
            HSSFFont font = hssfworkbook.CreateFont();
            font.FontHeight = 20 * 20;
            style.SetFont(font);

cellTitle.CellStyle = style;

//合并标题行
            sheet1.AddMergedRegion(new Region(0, 0, 1, 6));

DataTable dt=GetData();
            HSSFRow row;
            HSSFCell cell;
            HSSFCellStyle celStyle=getCellStyle();

HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
            HSSFClientAnchor anchor;
            HSSFSimpleShape line;
            int rowIndex;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //表头数据
                rowIndex = 3 * (i + 1);
                row = sheet1.CreateRow(rowIndex);

cell = row.CreateCell(0);
                cell.SetCellValue("姓名");
                cell.CellStyle = celStyle;

cell = row.CreateCell(1);
                cell.SetCellValue("基本工资");
                cell.CellStyle = celStyle;

cell = row.CreateCell(2);
                cell.SetCellValue("住房公积金");
                cell.CellStyle = celStyle;

cell = row.CreateCell(3);
                cell.SetCellValue("绩效奖金");
                cell.CellStyle = celStyle;

cell = row.CreateCell(4);
                cell.SetCellValue("社保扣款");
                cell.CellStyle = celStyle;

cell = row.CreateCell(5);
                cell.SetCellValue("代扣个税");
                cell.CellStyle = celStyle;

cell = row.CreateCell(6);
                cell.SetCellValue("实发工资");
                cell.CellStyle = celStyle;

DataRow dr = dt.Rows[i];
                //设置值和计算公式
                row = sheet1.CreateRow(rowIndex + 1);
                cell = row.CreateCell(0);
                cell.SetCellValue(dr["FName"].ToString());
                cell.CellStyle = celStyle;

cell = row.CreateCell(1);
                cell.SetCellValue((double)dr["FBasicSalary"]);
                cell.CellStyle = celStyle;

cell = row.CreateCell(2);
                cell.SetCellValue((double)dr["FAccumulationFund"]);
                cell.CellStyle = celStyle;

cell = row.CreateCell(3);
                cell.SetCellValue((double)dr["FBonus"]);
                cell.CellStyle = celStyle;

cell = row.CreateCell(4);
                cell.SetCellFormula(String.Format("$B{0}*0.08",rowIndex+2));
                cell.CellStyle = celStyle;

cell = row.CreateCell(5);
                cell.SetCellFormula(String.Format("SUM($B{0}:$D{0})*0.1",rowIndex+2));
                cell.CellStyle = celStyle;

cell = row.CreateCell(6);
                cell.SetCellFormula(String.Format("SUM($B{0}:$D{0})-SUM($E{0}:$F{0})",rowIndex+2));
                cell.CellStyle = celStyle;

//绘制分隔线
                sheet1.AddMergedRegion(new Region(rowIndex+2, 0, rowIndex+2, 6));
                anchor = new HSSFClientAnchor(0, 125, 1023, 125, 0, rowIndex + 2, 6, rowIndex + 2);
                line = patriarch.CreateSimpleShape(anchor);
                line.ShapeType = HSSFSimpleShape.OBJECT_TYPE_LINE;
                line.LineStyle = HSSFShape.LINESTYLE_DASHGEL;

}

WriteToFile();
        }

static DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FName",typeof(System.String));
            dt.Columns.Add("FBasicSalary",typeof(System.Double));
            dt.Columns.Add("FAccumulationFund", typeof(System.Double));
            dt.Columns.Add("FBonus", typeof(System.Double));

dt.Rows.Add("令狐冲", 6000, 1000, 2000);
            dt.Rows.Add("任盈盈", 7000, 1000, 2500);
            dt.Rows.Add("林平之", 5000, 1000, 1500);
            dt.Rows.Add("岳灵珊", 4000, 1000, 900);
            dt.Rows.Add("任我行", 4000, 1000, 800);
            dt.Rows.Add("风清扬", 9000, 5000, 3000);

return dt;
        }

static HSSFCellStyle getCellStyle()
        {
            HSSFCellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderLeft = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderRight = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderTop = HSSFCellStyle.BORDER_THIN;
            return cellStyle;
        }

static void WriteToFile()
        {
            //Write the stream data of workbook to the root directory
            FileStream file = new FileStream(@"test.xls", FileMode.Create);
            hssfworkbook.Write(file);
            file.Close();
        }

static void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();

//create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            hssfworkbook.DocumentSummaryInformation = dsi;

//create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "NPOI SDK Example";
            hssfworkbook.SummaryInformation = si;
        }
    }
}

生成的Excel文件样式如下:

学习教程:http://www.cnblogs.com/atao/archive/2009/10/13/1582832.html

3.3 用NPOI操作EXCEL--生成一张工资单的更多相关文章

  1. NPOI操作Excel辅助类

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

  2. NPOI操作excel之写入数据到excel表

    在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...

  3. C#开发中使用Npoi操作excel实例代码

    C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...

  4. 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数

    2.4.1 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数   NPOI教程:http://www.cnb ...

  5. [转] C#操作EXCEL,生成图表的全面应用

    gailzhao 原文 关于C#操作EXCEL,生成图表的全面应用 近来我在开发一个运用C#生成EXCEL文档的程序,其中要根据数据生成相应的图表,该图表对颜色和格式都有严格的要求,在百度和谷歌中搜索 ...

  6. C# 如何使用NPOI操作Excel以及读取合并单元格等

    C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...

  7. 用NPOI操作EXCEL-锁定列CreateFreezePane()

    public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...

  8. .NET 通过 NPOI 操作 Excel

    目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...

  9. 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容

    2.6.2 用NPOI操作EXCEL--设置密码       有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...

  10. 使用NPOI操作Excel文件及其日期处理

    工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...

随机推荐

  1. zoj 2589 Matrix Searching 二维线段树

    题目链接 给一个n*n的矩阵, 给q个查询, 每次给出x1, y1, x2, y2, 求这个矩阵中的最小值. 代码基本上和上一题相同... #include<bits/stdc++.h> ...

  2. 走进Groovy (一)

    一直很喜欢脚本语言,但是一直在不大的公司工作,用得一直是“高大上”的JAVA语言,在真正的项目中,没什么机会用到脚本语言.这两年,又断断续续的用了2年的Ruby,再回头继续用JAVA,说实话,真感觉J ...

  3. QT5.4 计算器程序 打包&发布,解决dll的最新解决方案(图文并茂,很清楚)

    QT写界面还是很不错,就是打包会比较麻烦,折腾了一天总算是打包完成了. QT软件的打包发布一个难点是必备dll文件的识别,现在高版本QT自带了一个windeployqt工具,直接会把需要的dll生成一 ...

  4. HTTP使用BASIC认证的原理及实现方法(还有NTLM方法,比较复杂)

    一.   BASIC认证概述 在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份证的方法,当一个客户端向HTTP服务 器进行数据请求时,如果客 ...

  5. Android快速开发框架——AndroidAnnotations(Code Diet)

    简介:AndroidAnnotations是一个依赖注入方式来简化代码结构 ,快速开发的开源框架,使结构代码更清晰,减少代码重复性.对今后我们做自动化测试和自动化埋点开发都会提高开发效率.跟我们之前使 ...

  6. Gson使用初探

    参考地址: http://www.stormzhang.com/android/2014/05/22/android-gson/ 我的示例代码: public void doGsonTest(View ...

  7. 部署nginx+rsyslog补丁

    nginx 配置: user nginx; worker_processes 1; syslog local5 nginx; error_log /var/log/nginx/nginx_error. ...

  8. appledoc:Objective-C注释文档生成工具

    appledoc是帮助Objective-C开发者从特殊格式的源代码注释中生成类似apple资源代码帮助文档的命令行工具. 安装和使用都非常简单: 安装 git clone git://github. ...

  9. 高性能JSON库---FastJson(阿里巴巴)

    1.FastJSON简单介绍 Fastjson是一个Java语言编写的高性能功能完好的JSON库. 它採用一种"假定有序高速匹配"的算法,把JSON Parse的性能提升到极致,是 ...

  10. js中使用控件名和数组下标方式获取控件的值时失败

    在做界面展示时涉及到表单行项目的增加和删除时,我们一帮都使用js的脚本实现表单行的增加和删除,那么在进行表单的提交的时我们会再页面上进行提交数据的初步校验,进行数据的初步校验时,就要动态获取控件的值. ...