直接上代码,希望能够帮助到你:
public string ExportStudent()
{
//创建execl工作薄
IWorkbook wb = new HSSFWorkbook();
//创建execl单元格格式
ICellStyle cellStyle = wb.CreateCellStyle();
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
//水平对齐
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//垂直对齐
cellStyle.VerticalAlignment = VerticalAlignment.Center;
//设置字体
IFont font = wb.CreateFont();
font.FontHeightInPoints = 10;
font.FontName = "楷体";
cellStyle.SetFont(font);
//创建表
ISheet sh = wb.CreateSheet("学生信息表");
sh.SetColumnWidth(0, 15 * 256);
//创建默认的第一行
IRow row0 = sh.CreateRow(0);
//创建默认的三个单元格
ICell rowce0l0 = row0.CreateCell(0);
ICell rowce0l1 = row0.CreateCell(1);
ICell rowce0l2 = row0.CreateCell(2);
//给第一行添加内容
rowce0l0.SetCellValue("序号");
rowce0l0.CellStyle = cellStyle;
rowce0l1.SetCellValue("班级");
rowce0l1.CellStyle = cellStyle;
rowce0l2.SetCellValue("姓名");
rowce0l2.CellStyle = cellStyle;
//创建第二行
IRow row1 = sh.CreateRow(1);
//创建三个单元格
ICell rowce1l0 = row0.CreateCell(0);
ICell rowce1l1 = row0.CreateCell(1);
ICell rowce1l2 = row0.CreateCell(2);
//给第二行添加内容
rowce1l0.SetCellValue("1");
rowce1l0.CellStyle = cellStyle;
rowce1l1.SetCellValue("10班");
rowce1l1.CellStyle = cellStyle;
rowce1l2.SetCellValue("张三");
rowce1l2.CellStyle = cellStyle;
//写入
string path="~/student/"
using (FileStream fielstram = File.OpenWrite(@"" + path + "学生信息.xls"))
{
wb.Write(fielstram);
}
}```