【黑马程序员】数据导出至Excel(学习笔记)

------- WindowsPhone 7手机开发.Net培训、期待与您交流! -------

1.首先您下载NPOI开发包(这里我只用到了.net4.0中的Ionic.Zip.dll和NPOI.dll)

2.将Ionic.Zip.dll和NPOI.dll引用到您的项目下面。

3.c# Code如下:


private void btnExportToExcel_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sdfExport = new SaveFileDialog();
            sdfExport.Filter = "Excel文件|*.xls";
            if (sdfExport.ShowDialog() != true)
            {
                return;
            }
            string filename = sdfExport.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("入职日期");

            //把查询结果导出到Excel
            Employee[] employees = (Employee[])datagrid.ItemsSource;
            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);

                ICellStyle styledate = workbook.CreateCellStyle();
               IDataFormat format = workbook.CreateDataFormat();
            //格式具体有哪些请看单元格右键中的格式,有说明
               styledate.DataFormat = format.GetFormat("yyyy\"年\"m\"月\"d\"日\"");

               ICell cellInDate = row.CreateCell(2, CellType.NUMERIC);
                cellInDate.CellStyle = styledate;
                cellInDate.SetCellValue(employee.InDate);
            }

            using (Stream stream = File.OpenWrite(filename))
            {
                workbook.Write(stream);
            }
        }


     

你可能感兴趣的:(【黑马程序员】数据导出至Excel(学习笔记))