Nuget 安装 NPOI 2.4.1
工作时间写着测试玩玩
public void ExportDataToExcel() { var workbook = new HSSFWorkbook(); var sheet = workbook.CreateSheet("测试NPOI"); sheet.DefaultColumnWidth = 20; sheet.ForceFormulaRecalculation = true; var headFont = workbook.CreateFont(); headFont.IsBold = true; //标题列样式 var headStyle = workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; headStyle.BorderBottom = BorderStyle.Thin; headStyle.BorderLeft = BorderStyle.Thin; headStyle.BorderRight = BorderStyle.Thin; headStyle.BorderTop = BorderStyle.Thin; headStyle.SetFont(headFont); var rowIndex = 0; var row = sheet.CreateRow(rowIndex); var cell = row.CreateCell(0); cell.SetCellValue("姓名"); cell.CellStyle = headStyle; cell = row.CreateCell(1); cell.SetCellValue("年龄"); cell.CellStyle = headStyle; //单元格边框 var cellStyle=workbook.CreateCellStyle(); cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BorderLeft = BorderStyle.Thin; cellStyle.BorderRight = BorderStyle.Thin; cellStyle.BorderTop = BorderStyle.Thin; for (var i = 1; i < 6; i++) { row = sheet.CreateRow(i); cell = row.CreateCell(0); cell.SetCellValue($"测试{i}"); cell.CellStyle = cellStyle; cell = row.CreateCell(1); cell.SetCellValue(i); cell.CellStyle = cellStyle; } //公式计算 row = sheet.CreateRow(7); cell = row.CreateCell(3); cell.SetCellValue(100); cell = row.CreateCell(4); cell.SetCellValue(200); cell = row.CreateCell(5); cell.CellFormula = "D8+E8"; //获取公式值 如果要遍历找出是否公式单元格 CellType判断 var e = new HSSFFormulaEvaluator(workbook); cell = e.EvaluateInCell(cell); var cell1=row.CreateCell(6); cell1.SetCellValue(cell.NumericCellValue); string Path = @"D:\AAA\导出"; //Excel的路径及名称 string excelPath = Path + "AA1.xls"; FileStream fileStream = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (!workbook.IsWriteProtected) { workbook.Write(fileStream); } fileStream.Close(); }