首先安装NPOI 选择项目
如果项目版本过低可以选择低版本的NPOI安装
public void ExportExecl()
{
#region 创建excel
//创建excel工作薄
IWorkbook wb = new HSSFWorkbook();
//IWorkbook wb2 = new XSSFWorkbook();
//创建excel 单元格式
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 = 18;
font.FontName = "微软雅黑";
cellStyle.SetFont(font);
#endregion
#region 创建表
//创建表
ISheet sh = wb.CreateSheet("学生表");
//设置第一列的宽度
sh.SetColumnWidth(0, 15 * 256);
//创建第一行
IRow row0 = sh.CreateRow(0);
//创建四个单元格
ICell row0ICell0 = row0.CreateCell(0);
ICell row0ICell1 = row0.CreateCell(1);
ICell row0ICell2 = row0.CreateCell(2);
ICell row0ICell3 = row0.CreateCell(3);
//给第一单元格添加内容
row0ICell0.SetCellValue("序号");
row0ICell0.CellStyle = cellStyle;
row0ICell1.SetCellValue("姓名");
row0ICell1.CellStyle = cellStyle;
row0ICell2.SetCellValue("年龄");
row0ICell2.CellStyle = cellStyle;
row0ICell3.SetCellValue("性别");
row0ICell3.CellStyle = cellStyle;
//创建第二行
IRow row1 = sh.CreateRow(1);
//创建四个单元格
ICell row1ICell0 = row1.CreateCell(0);
ICell row1ICell1 = row1.CreateCell(1);
ICell row1ICell2 = row1.CreateCell(2);
ICell row1ICell3 = row1.CreateCell(3);
//给第一单元格添加内容
row1ICell0.SetCellValue("1");
row1ICell0.CellStyle = cellStyle;
row1ICell1.SetCellValue("张三");
row1ICell1.CellStyle = cellStyle;
row1ICell2.SetCellValue("18");
row1ICell2.CellStyle = cellStyle;
row1ICell3.SetCellValue("男");
row1ICell3.CellStyle = cellStyle;
//创建第三行
IRow row2 = sh.CreateRow(2);
//创建四个单元格
ICell row2ICell0 = row2.CreateCell(0);
ICell row2ICell1 = row2.CreateCell(1);
ICell row2ICell2 = row2.CreateCell(2);
ICell row2ICell3 = row2.CreateCell(3);
//给第一单元格添加内容
row2ICell0.SetCellValue("2");
row2ICell0.CellStyle = cellStyle;
row2ICell1.SetCellValue("李花");
row2ICell1.CellStyle = cellStyle;
row2ICell2.SetCellValue("19");
row2ICell2.CellStyle = cellStyle;
row2ICell3.SetCellValue("女");
row2ICell3.CellStyle = cellStyle;
#endregion
try
{
using (FileStream filestream = File.OpenWrite(@"E:\学生信息.xls"))
{
wb.Write(filestream);
Response.Write("<script>alert('导出成功')</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ExportExecl();
}