1 namespace ExcelTest 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 var userList = GetUsers(); 8 var stream = RenderExcel(userList); 9 SaveToFile(stream, "./1.xls"); 10 } 11 12 static void SaveToFile(MemoryStream ms, string fileName) 13 { 14 using (FileStream fs = new FileStream(fileName, FileMode.Create)) 15 { 16 byte[] data = ms.ToArray(); 17 fs.Write(data, 0, data.Length); 18 fs.Flush(); 19 } 20 } 21 22 public static MemoryStream RenderExcel(List<User> userList) 23 { 24 MemoryStream ms = new MemoryStream(); 25 26 DataTable dt = new DataTable(); 27 28 var workBook = new HSSFWorkbook(); 29 var sheet = workBook.CreateSheet("Sheet1"); 30 var headerRow = sheet.CreateRow(0); 31 var headerCell = headerRow.CreateCell(0); 32 headerCell.SetCellValue("用户表"); 33 34 //headerCell样式 35 ICellStyle style = workBook.CreateCellStyle(); 36 style.Alignment = HorizontalAlignment.Center; 37 // 38 var font = workBook.CreateFont(); 39 font.Boldweight = short.MaxValue; 40 style.SetFont(font); 41 headerCell.CellStyle = style; 42 // 43 headerRow.Height = 20 * 20; 44 sheet.SetColumnWidth(0, 10 * 256); 45 46 sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 1)); 47 48 var captionRow = sheet.CreateRow(1); 49 captionRow.CreateCell(0).SetCellValue("ID"); 50 captionRow.CreateCell(1).SetCellValue("名字"); 51 52 int rowIndex = 2; 53 foreach (var user in userList) 54 { 55 var dataRow = sheet.CreateRow(rowIndex); 56 57 dataRow.CreateCell(0).SetCellValue(user.Id); 58 dataRow.CreateCell(1).SetCellValue(user.Name); 59 60 rowIndex++; 61 } 62 workBook.Write(ms); 63 ms.Flush(); 64 ms.Position = 0; 65 return ms; 66 } 67 68 static List<User> GetUsers() 69 { 70 List<User> users = new List<User> 71 { 72 new User {Id=1,Name="qwe" }, 73 new User {Id=2,Name="wer" }, 74 new User {Id=3,Name="rty" }, 75 new User {Id=4,Name="tyu" }, 76 new User {Id=5,Name="uio" }, 77 }; 78 return users; 79 } 80 } 81 82 class User 83 { 84 public int Id { get; set; } 85 public string Name { get; set; } 86 87 } 88 }