一、下載NPOI類庫 使用Nuget線上搜索NPOI,下載安裝 二、代碼開擼 ...
一、下載NPOI類庫
使用Nuget線上搜索NPOI,下載安裝
二、代碼開擼
var workBook = new HSSFWorkbook(); #region 設置樣式 IFont font = workBook.CreateFont(); font.FontHeightInPoints = 11; font.FontName = "宋體"; font.Boldweight = (short)FontBoldWeight.Bold; font.Color = HSSFColor.White.Index; HSSFPalette palette = workBook.GetCustomPalette(); //調色板實例 palette.SetColorAtIndex((short)8, (byte)91, (byte)155, (byte)213);//設置表頭背景色 palette.SetColorAtIndex((short)16, (byte)221, (byte)235, (byte)247);//設置內容背景色 palette.SetColorAtIndex((short)32, (byte)155, (byte)194, (byte)230);//設置下邊框線顏色 palette.SetColorAtIndex((short)48, (byte)212, (byte)212, (byte)212);//設置下邊框線顏色 palette.SetColorAtIndex((short)64, (byte)255, (byte)255, (byte)0);//設置黃色 var cellMidStyle = workBook.CreateCellStyle(); cellMidStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//設置水平居中 cellMidStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//設置垂直居中 cellMidStyle.FillPattern = FillPattern.SolidForeground; cellMidStyle.FillForegroundColor = palette.FindColor((byte)221, (byte)235, (byte)247).Indexed; cellMidStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellMidStyle.BottomBorderColor = palette.FindColor((byte)155, (byte)194, (byte)230).Indexed; cellMidStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellMidStyle.LeftBorderColor = palette.FindColor((byte)212, (byte)212, (byte)212).Indexed; cellMidStyle.SetFont(font); #endregion var sheet = workBook.CreateSheet("sheet1");//創建表格 // 第一行存放列名 var row = sheet.CreateRow(0); for (int i = 0; i < titles.Count; i++) { var cell = row.CreateCell(i); cell.SetCellValue(titles[i]); int length = Encoding.UTF8.GetBytes(titles[i]).Length; sheet.SetColumnWidth(i, length * 256);//設置表格列寬 cell.CellStyle = cellStyle;//設置單元格樣式 } int rowIndex = 1; foreach (var record in list) { row = sheet.CreateRow(rowIndex); row.CreateCell(0).SetCellValue("單元格1");//給rowIndex行的第1列的單元格賦值 rowIndex++; } // 創建文件 using (FileStream fs = new FileStream(string.Format("{0}/{1}", path, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"), FileMode.Create)) { workBook.Write(fs); }