public void excleCreate()
{
//创建HSSFWorkbook对象(excel的文档对象)
HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
HSSFSheet sheet = wb.CreateSheet("成绩表") as HSSFSheet;
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
HSSFRow row1 = sheet.CreateRow(0) as HSSFRow;
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell cell = row1.CreateCell(0) as HSSFCell;
cell.SetCellValue("学员考试成绩一览表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 3));
//设置样式
//设置样式
HSSFCellStyle cellstyle = wb.CreateCellStyle() as HSSFCellStyle;
cellstyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
cellstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
#region 样式设置过程
//设置填充方式(填充图案)
cellstyle.FillForegroundColor = HSSFColor.RED.index;
cellstyle.FillBackgroundColor = HSSFColor.LIGHT_YELLOW.index;
//在sheet里创建第二行
HSSFFont fontStyle = wb.CreateFont() as HSSFFont;
fontStyle.FontName = "黑体";
//设置字体高度
fontStyle.FontHeightInPoints = (short)20;
//设置字体颜色
fontStyle.Color = HSSFColor.BLUE.index;
//设置斜体
fontStyle.IsItalic = true;
#endregion
//创建单元格并设置单元格内容
HSSFRow row2 = sheet.CreateRow(1) as HSSFRow;
row2.CreateCell(0).SetCellValue("姓名");
row2.CreateCell(1).SetCellValue("班级");
row2.CreateCell(2).SetCellValue("笔试成绩");
row2.CreateCell(3).SetCellValue("机试成绩");
string[] username = { "张三", "李四", "王二", "赵云" };
Random rd = new Random();
for (int i = 2; i < 6; i++)
{
int jshi_cj = (rd.Next(0, 101));
int bishi_cj = (rd.Next(0, 101));
int calssName = (rd.Next(100, 201));
HSSFRow row3 = sheet.CreateRow(i) as HSSFRow;
row3.CreateCell(0).SetCellValue(username[i - 2]);
row3.CreateCell(1).SetCellValue("As" + calssName);
row3.CreateCell(2).SetCellValue(bishi_cj);
row3.CreateCell(3).SetCellValue(jshi_cj);
}
//.....省略部分代码
//6.保存路径
string FilePath = "F:\\myexcle.xlsx";
FilePath = Path.GetFullPath(FilePath);//绝对路径
//7.保存写入
using (FileStream file = new FileStream(FilePath, FileMode.Create))
{
wb.Write(file);//将 HSSFWorkbook 数据写入流
}
}
输出结果: