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(); }