zoukankan      html  css  js  c++  java
  • 将DataTable中的数据导出到Excel

     1 public static void Export(System.Data.DataTable dt,NPOI.HSSF.UserModel.HSSFWorkbook workbook,string FilePath)
     2         {
     3             if(dt.Rows.Count == 0)
     4             {
     5                 System.Windows.MessageBox.Show("尚未读取到任何数据");
     6                 return;
     7             }
     8             ISheet sheet = workbook.CreateSheet("导出数据");
     9             HSSFCellStyle styleHeader =(HSSFCellStyle)workbook.CreateCellStyle();
    10             styleHeader.Alignment = HorizontalAlignment.Center;
    11             IFont font = workbook.CreateFont();
    12             font.FontHeight = 20 * 20;
    13             font.Color = HSSFColor.Red.Index;
    14             styleHeader.SetFont(font);
    15             HSSFCellStyle style = (HSSFCellStyle)workbook.CreateCellStyle();
    16             style.Alignment = HorizontalAlignment.Center;
    17             using(FileStream fs = new FileStream(FilePath + "\导出数据.xls",FileMode.Create))
    18             {
    19                 IRow rowHeader = sheet.CreateRow(0);
    20                 for (int col = 0; col < dt.Columns.Count; col++)
    21                 {
    22                     ICell cellHeader = rowHeader.CreateCell(col);
    23                     cellHeader.SetCellValue(dt.Columns[col].ColumnName);
    24                     sheet.SetColumnWidth(col, 30 * 256);
    25                     cellHeader.CellStyle = styleHeader;
    26                 }
    27                 for (int i = 1; i < dt.Rows.Count; i++)
    28                 {
    29                     IRow row = sheet.CreateRow(i);
    30                     for (int j = 0; j < dt.Columns.Count; j++)
    31                     {
    32                         ICell cell = row.CreateCell(j);
    33                         cell.SetCellValue(dt.Rows[i - 1][j].ToString());
    34                         cell.CellStyle = style;
    35                     }
    36                 }
    37                 workbook.Write(fs);
    38                 System.Windows.MessageBox.Show("保存成功");
    39             }
    40         }
  • 相关阅读:
    从scanf的学习接口设计
    特现C语言编程特点的小代码,itoa,数值转换成字符串
    So many good projects for studying C programming lanuage.
    重要算法代码
    选择一本C++教材
    4412 内核模块传参数
    4412 GPIO初始化
    4412 物理地址
    4412 杂项设备
    4412 Linux设备总线
  • 原文地址:https://www.cnblogs.com/zhaotianff/p/5843365.html
Copyright © 2011-2022 走看看