在C#中利用NPOI操作Excel表格非常方便,几乎上支持所有的Excel表格本身所有的功能,如字体设置、颜色设置、单元格合并、数值计算、页眉页脚等等。

这里准备使用NPOI生成一个班级成绩单Excel表格,表格中包含的信息包括学号、姓名、各科成绩、平均成绩、排名等。

实现原理很简单,主要是NPOI的一些操作,具体实现的功能包括下边几个:

  • 单元格合并
  • 字体大小、颜色设置
  • 背景颜色设置
  • 边框粗细设置
  • 多个单元格SUM求和
  • 数据写入和读取

完整C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Data; namespace Score_Excel
{
class Program
{
static void Main(string[] args)
{
IWorkbook workbook = new HSSFWorkbook();//声明工作簿对象,可以创建xls或xlsx Excel文件
ISheet sheet1 = workbook.CreateSheet("Score Record"); //创建工作表
ICell sheet1Title = sheet1.CreateRow(0).CreateCell(0); //创建第一行第一个单元格
sheet1Title.SetCellValue("国家体育总局附属二小幼儿园小一班体育成绩表"); //表头
sheet1Title.CellStyle = GetTitleCellStyle(workbook);
sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 9)); //合并单元格
DataTable dt = GetData();
IRow row;
ICell cell;
ICellStyle cellStyle1 = GetCellStyle(workbook, 2);
ICellStyle cellStyle2 = GetCellStyle(workbook, 0);
double[] aveScore = new double[8]; //平均成绩数组
int[] rankNum = new int[8]; //名次数组 //表头数据
row = sheet1.CreateRow(1);
cell = row.CreateCell(0);
cell.SetCellValue("学号");
cell.CellStyle = cellStyle1; cell = row.CreateCell(1);
cell.SetCellValue("姓名");
cell.CellStyle = cellStyle1; cell = row.CreateCell(2);
cell.SetCellValue("排球");
cell.CellStyle = cellStyle1; cell = row.CreateCell(3);
cell.SetCellValue("乒乓球");
cell.CellStyle = cellStyle1; cell = row.CreateCell(4);
cell.SetCellValue("跳水");
cell.CellStyle = cellStyle1; cell = row.CreateCell(5);
cell.SetCellValue("举重");
cell.CellStyle = cellStyle1; cell = row.CreateCell(6);
cell.SetCellValue("自由泳");
cell.CellStyle = cellStyle1; cell = row.CreateCell(7);
cell.SetCellValue("体操");
cell.CellStyle = cellStyle1; cell = row.CreateCell(8);
cell.SetCellValue("平均成绩");
cell.CellStyle = cellStyle1; cell = row.CreateCell(9);
cell.SetCellValue("名次");
cell.CellStyle = cellStyle1; // 写入数据
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dataR = dt.Rows[i];
row = sheet1.CreateRow(i + 2); cell = row.CreateCell(0);
cell.SetCellValue(dataR["学号"].ToString());
cell.CellStyle = cellStyle2; cell = row.CreateCell(1);
cell.SetCellValue(dataR["姓名"].ToString());
cell.CellStyle = cellStyle2; cell = row.CreateCell(2);
cell.SetCellValue((Double)dataR["排球"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(3);
cell.SetCellValue((Double)dataR["乒乓球"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(4);
cell.SetCellValue((Double)dataR["跳水"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(5);
cell.SetCellValue((Double)dataR["举重"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(6);
cell.SetCellValue((Double)dataR["自由泳"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(7);
cell.SetCellValue((Double)dataR["体操"]);
cell.CellStyle = cellStyle2; cell = row.CreateCell(8);
cell.SetCellFormula(String.Format("SUM($C{0}:$H{0})/6", i + 3));
cell.CellStyle = cellStyle2; for (int j = 2; j < 8; j++)
{
aveScore[i] += row.Cells[j].NumericCellValue;
}
aveScore[i] /= 6; //每个人平均成绩
} //以下for循环实现对每个人的成绩进行排名
for (int i = 0; i < 8; i++)
{
rankNum[i] = 1;
for (int j = 0; j < 8; j++)
{
if (aveScore[i] < aveScore[j])
{
rankNum[i]++;
}
}
} //排名写入“名次”列
for (int i = 0; i < 8; i++)
{
row = sheet1.GetRow(i + 2);
cell = row.CreateCell(9);
cell.SetCellValue(rankNum[i]);
cell.CellStyle = cellStyle2;
} if (!Directory.Exists(@"E:\Score Excel")) //检查是否存在文件夹,不存在则新建
{
Directory.CreateDirectory(@"E:\Score Excel");
} FileStream file = new FileStream(@"E:\Score Excel\Score Record.xls", FileMode.Create);
workbook.Write(file);
file.Close();
workbook.Close();
} static DataTable GetData() //原始数据
{
DataTable dt = new DataTable();
dt.Columns.Add("学号", typeof(System.Int32));
dt.Columns.Add("姓名", typeof(System.String));
dt.Columns.Add("排球", typeof(System.Double));
dt.Columns.Add("乒乓球", typeof(System.Double));
dt.Columns.Add("跳水", typeof(System.Double));
dt.Columns.Add("举重", typeof(System.Double));
dt.Columns.Add("自由泳", typeof(System.Double));
dt.Columns.Add("体操", typeof(System.Double)); dt.Rows.Add("231603001", "张继科", 100, 83, 69.5, 90, 61, 92);
dt.Rows.Add("231603002", "傅园慧", 99, 100, 99.9, 100, 100, 99.5);
dt.Rows.Add("231603003", "孙杨", 92, 64, 78.5, 64, 69, 90.5);
dt.Rows.Add("231603004", "福原爱", 76, 93.5, 69.5, 85, 87, 61);
dt.Rows.Add("231603005", "大魔王", 99, 102, 92, 78, 96.5, 89.5);
dt.Rows.Add("231603006", "林丹", 87, 98.5, 78.5, 69.5, 97, 89);
dt.Rows.Add("231603007", "丁宁", 85, 93, 87.5, 90.5, 69, 79.5);
dt.Rows.Add("231603008", "宁泽涛", 79, 62.5, 87.5, 98, 78, 93.5);
return dt;
} //设置单元格格式函数,边框粗细3个可选
static ICellStyle GetCellStyle(IWorkbook workbook, int borderThickness)
{
ICellStyle cellStyle = workbook.CreateCellStyle();
NPOI.SS.UserModel.BorderStyle borderType;
switch (borderThickness)
{
case 0:
borderType = NPOI.SS.UserModel.BorderStyle.Thin;
break;
case 1:
borderType = NPOI.SS.UserModel.BorderStyle.Medium;
break;
case 2:
borderType = NPOI.SS.UserModel.BorderStyle.Thick;
break;
default:
borderType = NPOI.SS.UserModel.BorderStyle.Thin;
break;
}
cellStyle.BorderBottom = borderType;
cellStyle.BorderTop = borderType;
cellStyle.BorderLeft = borderType;
cellStyle.BorderRight = borderType; IFont font = workbook.CreateFont();//设置字体大小和颜色
font.FontName = "宋体";
font.FontHeightInPoints = 13;
cellStyle.SetFont(font);
return cellStyle;
} //设置表头格式函数
static ICellStyle GetTitleCellStyle(IWorkbook workbook)
{
ICellStyle cell1Style = workbook.CreateCellStyle();
cell1Style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
cell1Style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
cell1Style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cell1Style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cell1Style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cell1Style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; IFont font = workbook.CreateFont(); //设置字体大小和颜色
font.FontName = "微软雅黑";
font.FontHeightInPoints = 13;
font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
cell1Style.SetFont(font);
cell1Style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;
cell1Style.FillPattern = FillPattern.SolidForeground;
return cell1Style;
}
}
}

执行后,在E盘指定目录下生成了名字是“Score Excel”的表格:

“名次”列的排名实现:

先声明了一个大小为8的Int数组,默认值设为1,依次拿当前的平均成绩和其他7个的平均成绩对比,有几个大于当前平均成绩的元素,就在当前数组值上加上几,最后得到的就是每个人的排名,实现如下:

//以下for循环实现对每个人的成绩进行排名
for (int i = 0; i < 8; i++)
{
rankNum[i] = 1;
for (int j = 0; j < 8; j++)
{
if (aveScore[i] < aveScore[j])
{
rankNum[i]++;
}
}
}

用NPOI、C#操作Excel表格生成班级成绩单的更多相关文章

  1. Python 利用Python操作excel表格之openyxl介绍Part2

    利用Python操作excel表格之openyxl介绍 by:授客 QQ:1033553122 欢迎加入全国软件测试交流qq群(群号:7156436) ## 绘图 c = LineChart()    ...

  2. 【转】python操作excel表格(xlrd/xlwt)

    [转]python操作excel表格(xlrd/xlwt) 最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异, ...

  3. 转载:python操作excel表格(xlrd/xlwt)

    python操作excel表格(xlrd/xlwt)   最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异,而 ...

  4. qt 操作excel表格

     自己编写的一个Qt C++类,用于操作excel表格,在Qt中操作excel需在.pro中增加CONFIG+=qaxcontainer配置. 1.打开Excel:objExcel = new QAx ...

  5. Python 利用Python操作excel表格之openyxl介绍Part1

    利用Python操作excel表格之openyxl介绍 by:授客 QQ:1033553122 欢迎加入全国软件测试交流qq群(群号:7156436),免费获取以下性能监控工具(类似Nmon精简版) ...

  6. Python 利用Python操作excel表格之xlwt介绍

    利用Python操作excel表格之xlwt介绍   by:授客 QQ:1033553122 直接上代码   案例1 #!/usr/bin/env python # -*- coding:utf-8 ...

  7. python - 操作excel表格

    说明:由于公司oa暂缺,人事妹子在做考勤的时候,需要通过几个excel表格去交叉比对员工是否有旷工或迟到,工作量大而且容易出错. 这时候it屌丝的机会来啦,花了一天时间给妹子撸了一个自动化脚本. 1. ...

  8. 使用Java操作Excel表格

    目录 一.配置第三方库 二.使用Apache POI API 1. 打开Excel文件 2. 选择对应的sheet 3. Sheet接口的基本使用 3.1 获取开头行和结束行 3.2 获取Row对象 ...

  9. python操作excel表格(xlrd/xlwt)

    最近遇到一个情景,就是定期生成并发送服务器使用情况报表,按照不同维度统计,涉及python对excel的操作,上网搜罗了一番,大多大同小异,而且不太能满足需求,不过经过一番对源码的"研究&q ...

随机推荐

  1. HBase框架基础(三)

    * HBase框架基础(三) 本节我们继续讨论HBase的一些开发常识,以及HBase与其他框架协调使用的方式.在开始之前,为了框架之间更好的适配,以及复习之前HBase的配置操作,请使用cdh版本的 ...

  2. POJ TOYS(叉积的妙用+二分答案)

    TOYS Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 16042   Accepted: 7688 Description ...

  3. AppManager类,管理Activity和App

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); / ...

  4. Redis缓存Mysql模拟用户登录Java实现实例

    https://blog.csdn.net/suneclipse/article/details/50920396

  5. caffe命令及其参数解析

    caffe的c++主程序(caffe.cpp)放在根目录下的tools文件夹内, 当然还有一些其它的功能文件,如:convert_imageset.cpp, train_net.cpp, test_n ...

  6. [HEOI2012]旅行问题 AC 自动机

    题意: 求两个字符串的最长公共后缀,使得该后缀是某个字符串的前缀. 题解: 直接利用 $fail$ 指针的定义即可. 相当于求自动机上两点的 LCA,好像倍增可以,怕炸空间就老老实实写树剖吧. Cod ...

  7. neo4j nosql图数据库学习

    neo4j 文档:https://neo4j.com/docs/getting-started/current/cypher-intro/ 1.索引 # 给某类标签节点的属性添加索引 CREATE I ...

  8. Python学习笔记(4)--数据结构之元组tuple

    元组(tuple) 定义:tuple和list十分相似,但是tuple是不可变的,即不能修改tuple 初始化:(), ('a', ) , ('a', 'b')   //当只有一个元素时,需加上逗号, ...

  9. 在Fedora18上配置个人的Hadoop开发环境

    在Fedora18上配置个人的Hadoop开发环境 1.    背景 文章中讲述了类似于"personalcondor"的一种"personal hadoop" ...

  10. 在Unix上用 BIND建立名称服务器(naem server)

    在Unix上用 BIND建立名称服务器(naem server) 安装 apt install -y bind9 yum install -y bind bind-utils 下载源码并解压缩,htt ...