private void btnExportToExcel_Click(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "excel文件|*.xls"; if (sfd.ShowDialog() != true) { return; } string fileName = sfd.FileName; HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("员工信息表"); IRow rowHeader = sheet.CreateRow(0); rowHeader.CreateCell(0, CellType.STRING).SetCellValue("姓名"); rowHeader.CreateCell(1, CellType.STRING).SetCellValue("工号"); rowHeader.CreateCell(2, CellType.STRING).SetCellValue("入职时间"); rowHeader.CreateCell(3, CellType.STRING).SetCellValue("学历"); rowHeader.CreateCell(4, CellType.STRING).SetCellValue("毕业院校"); rowHeader.CreateCell(5, CellType.STRING).SetCellValue("基本工资"); rowHeader.CreateCell(6, CellType.STRING).SetCellValue("部门"); rowHeader.CreateCell(7, CellType.STRING).SetCellValue("职位"); rowHeader.CreateCell(8, CellType.STRING).SetCellValue("合同签订日期"); rowHeader.CreateCell(9, CellType.STRING).SetCellValue("合同到期日期"); Employee[] employees = (Employee[])datagrid.ItemsSource; ICellStyle cellStyle = workbook.CreateCellStyle(); IDataFormat dataFormat = workbook.CreateDataFormat(); cellStyle.DataFormat = dataFormat.GetFormat("yyyy\"年\"m\"月\"d\"日\""); for (int i = 0; i < employees.Length; i++) { Employee employee = employees[i]; IRow row = sheet.CreateRow(i + 1); row.CreateCell(0, CellType.STRING).SetCellValue(employee.Name); row.CreateCell(1, CellType.STRING).SetCellValue(employee.Number); ICell dateCell = row.CreateCell(2, CellType.NUMERIC); dateCell.CellStyle = cellStyle; dateCell.SetCellValue(employee.InDate); row.CreateCell(3, CellType.STRING).SetCellValue(IdNameDAL.GetEducationNameById(employee.EducationId)); row.CreateCell(4, CellType.STRING).SetCellValue(employee.School); row.CreateCell(5, CellType.STRING).SetCellValue(employee.BaseSalary); row.CreateCell(6, CellType.STRING).SetCellValue(DepartmentDAL.GetById(employee.DepartmentId).Name); row.CreateCell(7, CellType.STRING).SetCellValue(employee.Position); ICell contractBegindateCell = row.CreateCell(8, CellType.NUMERIC); contractBegindateCell.CellStyle = cellStyle; contractBegindateCell.SetCellValue(employee.ContractStartDay); ICell contractEnddateCell = row.CreateCell(9, CellType.NUMERIC); contractEnddateCell.CellStyle = cellStyle; contractEnddateCell.SetCellValue(employee.ContractEndDay); } using (Stream stream = File.OpenWrite(fileName)) { workbook.Write(stream); } }