将数据导出到Excel中,相信这样的需求大家都见的不少吧,今天为大家分享下我是如何将数据导出到Excel的
我用到了NPOI.dll插件,该插件可以从网上搜取
View Code
怎么样,比较简单而且比较容易控制吧 1 private void btnToExcel_Click(object sender, RoutedEventArgs e) 2 { 3 //数据源 4 ListlistPhone=(List )dgTest.ItemsSource; 5 //获取用户选择保存的路径文件名 6 string saveFileName=OpenFileDialog(); 7 if (!string.IsNullOrEmpty(saveFileName)) 8 { 9 //创建一个操作的对象10 HSSFWorkbook workBook = new HSSFWorkbook();11 //创建一个工作区12 ISheet sheet = workBook.CreateSheet("通信");13 //创建一行 并设置该行的值 作为标题14 IRow rowHead = sheet.CreateRow(0);15 rowHead.CreateCell(0,CellType.STRING).SetCellValue("地区");16 rowHead.CreateCell(1, CellType.STRING).SetCellValue("类型");17 rowHead.CreateCell(2, CellType.STRING).SetCellValue("区号");18 rowHead.CreateCell(3, CellType.STRING).SetCellValue("日期");19 int i = 0;20 //循环读取数据存入sheet工作表中21 foreach (var item in listPhone)22 {23 IRow row = sheet.CreateRow(++i);24 row.CreateCell(0,CellType.STRING).SetCellValue(item.AreaName);25 row.CreateCell(1, CellType.STRING).SetCellValue(item.NumbType);26 row.CreateCell(2, CellType.STRING).SetCellValue(item.AreaNumb);27 ICellStyle styledate = workBook.CreateCellStyle();28 IDataFormat format = workBook.CreateDataFormat();29 //格式具体有哪些请看单元格右键中的格式,有说明30 styledate.DataFormat = format.GetFormat("yyyy\"年\"m\"月\"d\"日\"");31 ICell cellDate=row.CreateCell(3, CellType.NUMERIC);32 cellDate.SetCellValue(DateTime.Now.ToShortDateString());33 cellDate.CellStyle = styledate;34 35 }36 using (Stream stream = File.OpenWrite(saveFileName))37 {38 workBook.Write(stream);39 MessageBox.Show("保存成功");40 }41 }42 }43 private string OpenFileDialog()44 {45 SaveFileDialog sfd = new SaveFileDialog();46 sfd.Filter = "Excel(*.xls, *.xlsx)|*.xls;*.xlsx";47 if (sfd.ShowDialog() == true)48 {49 return sfd.FileName;50 }51 else52 {53 return null;54 }55 }