NPOI操作创建Excel
程序员文章站
2022-04-28 13:02:52
一、下载NPOI类库 使用Nuget在线搜索NPOI,下载安装 二、代码开撸 ......
一、下载npoi类库
使用nuget在线搜索npoi,下载安装
二、代码开撸
var workbook = new hssfworkbook();
#region 设置样式
ifont font = workbook.createfont();
font.fontheightinpoints = 11;
font.fontname = "宋体";
font.boldweight = (short)fontboldweight.bold;
font.color = hssfcolor.white.index;
hssfpalette palette = workbook.getcustompalette(); //调色板实例
palette.setcoloratindex((short)8, (byte)91, (byte)155, (byte)213);//设置表头背景色
palette.setcoloratindex((short)16, (byte)221, (byte)235, (byte)247);//设置内容背景色
palette.setcoloratindex((short)32, (byte)155, (byte)194, (byte)230);//设置下边框线颜色
palette.setcoloratindex((short)48, (byte)212, (byte)212, (byte)212);//设置下边框线颜色
palette.setcoloratindex((short)64, (byte)255, (byte)255, (byte)0);//设置黄色
var cellmidstyle = workbook.createcellstyle();
cellmidstyle.alignment = npoi.ss.usermodel.horizontalalignment.center;//设置水平居中
cellmidstyle.verticalalignment = npoi.ss.usermodel.verticalalignment.center;//设置垂直居中
cellmidstyle.fillpattern = fillpattern.solidforeground;
cellmidstyle.fillforegroundcolor = palette.findcolor((byte)221, (byte)235, (byte)247).indexed;
cellmidstyle.borderbottom = npoi.ss.usermodel.borderstyle.thin;
cellmidstyle.bottombordercolor = palette.findcolor((byte)155, (byte)194, (byte)230).indexed;
cellmidstyle.borderleft = npoi.ss.usermodel.borderstyle.thin;
cellmidstyle.leftbordercolor = palette.findcolor((byte)212, (byte)212, (byte)212).indexed;
cellmidstyle.setfont(font);
#endregion
var sheet = workbook.createsheet("sheet1");//创建表格
// 第一行存放列名
var row = sheet.createrow(0);
for (int i = 0; i < titles.count; i++)
{
var cell = row.createcell(i);
cell.setcellvalue(titles[i]);
int length = encoding.utf8.getbytes(titles[i]).length;
sheet.setcolumnwidth(i, length * 256);//设置表格列宽
cell.cellstyle = cellstyle;//设置单元格样式
}
int rowindex = 1;
foreach (var record in list)
{
row = sheet.createrow(rowindex);
row.createcell(0).setcellvalue("单元格1");//给rowindex行的第1列的单元格赋值
rowindex++;
}
// 创建文件
using (filestream fs = new filestream(string.format("{0}/{1}", path, datetime.now.tostring("yyyymmddhhmmss") + ".xls"), filemode.create))
{
workbook.write(fs);
}
上一篇: iPhone降价促成5G前夜昙花一现 翻身要看任正非脸色
下一篇: 永恒有多长