隐藏

C# DataTable导出Excel

发布:2020/6/28 9:25:38作者:管理员 来源:本站 浏览次数:1025

/// <summary>
       /// DataTable导出到Excel
       /// </summary>
       /// <param name="dt">DataTable</param>
       /// <param name="array">首行数组</param>
       /// <param name="fileFullName">文件名</param>
       public static void ExportToExcel(DataTable dt, string[] array, string fileFullName)
       {
           #region
           XSSFWorkbook workbook = new XSSFWorkbook();
           FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
           ISheet sheet = workbook.CreateSheet("Sheet0");
           IRow row;
           row = sheet.CreateRow(0);
            
           for (int i = 0; i < array.Length; i++)
           {
               row.CreateCell(i).SetCellValue(array[i]);
           }
 
           for (int i = 0; i < dt.Rows.Count; i++)
           {
               row = sheet.CreateRow(i + 1);
 
               for (int j = 0; j < dt.Columns.Count; j++)
               {
                   row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
               }
           }
           workbook.Write(fs); //写入到excel
 
           #endregion
           // MessageBox.Show("导出成功!");
       }