c# NPOI 导出数据到Excel(简单版)

提示:NPOI 导出数据到Excel,需要引用NPOI类库
        /// 
        /// 导出数据到Excel
        /// 
        /// dataTable数据
        /// 导出Excel表名称
        /// 
        public byte[] CreateExcel(DataTable dataTable, string name)
        {
     
            HSSFWorkbook workbook = null;
            try
            {
     
                workbook = new HSSFWorkbook();//创建工作簿
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(name);//创建Sheet
                //CreateFreezePane方法参数说明
                //第一个参数表示要冻结的列数;
                //第二个参数表示要冻结的行数;
                sheet.CreateFreezePane(0, 1);
                HSSFRow row_title = sheet.CreateRow(0) as HSSFRow;
                row_title.HeightInPoints = 19.5F;
                //列操作
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
     
                    HSSFCell cell_row_title = row_title.CreateCell(i) as HSSFCell;
                    sheet.AutoSizeColumn(i, true);//列宽自适应
                    cell_row_title.SetCellValue(dataTable.Columns[i].ColumnName);
                }
                //行操作
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
     
                    HSSFRow row = sheet.CreateRow(i + 1) as HSSFRow;
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
     
                        HSSFCell cell_row = row.CreateCell(j) as HSSFCell;
                        //sheet.AutoSizeColumn(j, true);//会卡影响 速度
                        cell_row.SetCellValue(dataTable.Rows[i][j].ToString());
                    }
                }
                using (MemoryStream ms = new MemoryStream())
                {
     
                    workbook.Write(ms);
                    byte[] buff = ms.ToArray();
                    return buff;
                }

            }
            catch (Exception e) {
      }
            finally
            {
     
                if (workbook != null)
                {
     
                    workbook.Close();
                }

            }
            return null;
        }

你可能感兴趣的:(帮助类,excel,c#)