using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
//创建Execl
IWorkbook hssfworkbook =new HSSFWorkbook();
//创建一个Sheet
hssfworkbook.CreateSheet("Sheet1");
//HSSFWorkbook实例写入文件
FileStream file = new FileStream(@"test.xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
//要创建单元格首先要创建单元格所在的行,比如,下面的代码创建了第0行:
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
IRow row1=sheet1.CreateRow(0);
//行建好了,就可以建单元格了,比如创建A1位置的单元格:
row1.CreateCell(0).SetCellValue("This is a Sample");
//或者sheet1.GetRow(0).CreateCell(0).SetCellValue("This is a Sample");
//set header text 设置页眉
s1.Header.Center = "This is a test sheet";
//set footer text 设置页脚
s1.Footer.Left = "Copyright NPOI Team";
s1.Footer.Right = "created by 123";
//set date format 设置单元格格式
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
IDataFormat format = hssfworkbook.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("yyyy年m月d日");
//cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); 单元格格式为“0.00”来表示,"¥#,##0"美元显示,"0.00%"百分比显示
cell.CellStyle=cellStyle;
//合并单元格
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("Sales Report");
ICellStyle style = hssfworkbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER;
IFont font = hssfworkbook.CreateFont();
font.FontHeight = 20*20;
style.SetFont(font);
cell.CellStyle = style;
sheet.AddMergedRegion(new Region(0, 0, 0, 5));