//Datatable导出Excel private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName)         {             try             { HSSFWorkbook workbook = new HSSFWorkbook();                  ISheet sheet = workbook.CreateSheet("Sheet1");                  ICellStyle HeadercellStyle = workbook.CreateCellStyle();                 HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;                 HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;                 HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;                 HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;                 HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;                 //字体                 NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();                 headerfont.Boldweight = (short)FontBoldWeight.Bold;                 HeadercellStyle.SetFont(headerfont);                   //用column name 作为列名                 int icolIndex = 0;                 IRow headerRow = sheet.CreateRow(0);                 foreach (DataColumn item in dt.Columns)                 {                     ICell cell = headerRow.CreateCell(icolIndex);                     cell.SetCellValue(item.ColumnName);                     cell.CellStyle = HeadercellStyle;                     icolIndex++;                 }                  ICellStyle cellStyle = workbook.CreateCellStyle();                  //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看                 cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");                 cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;                 cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;                 cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;                 cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;                   NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();                 cellfont.Boldweight = (short)FontBoldWeight.Normal;                 cellStyle.SetFont(cellfont);                  //建立内容行                 int iRowIndex = 1;                 int iCellIndex = 0;                 foreach (DataRow Rowitem in dt.Rows)                 {                     IRow DataRow = sheet.CreateRow(iRowIndex);                     foreach (DataColumn Colitem in dt.Columns)                     {                          ICell cell = DataRow.CreateCell(iCellIndex);                         cell.SetCellValue(Rowitem[Colitem].ToString());                         cell.CellStyle = cellStyle;                         iCellIndex++;                     }                     iCellIndex = 0;                     iRowIndex++;                 }                  //自适应列宽度                 for (int i = 0; i < icolIndex; i++)                 {                     sheet.AutoSizeColumn(i);                 }                  //写Excel                 FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);                 workbook.Write(file);                 file.Flush();                 file.Close();                  MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_successfully"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);             }             catch (Exception ex)             {                 ILog log = LogManager.GetLogger("Exception Log");                 log.Error(ex.Message + Environment.NewLine + ex.StackTrace);                 //记录AuditTrail                 CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex);                  MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);             }             finally { workbook = null; }          }
/// <summary>         /// Excel文件导成Datatable         /// </summary>         /// <param name="strFilePath">Excel文件目录地址</param>         /// <param name="strTableName">Datatable表名</param>         /// <param name="iSheetIndex">Excel sheet index</param>         /// <returns></returns>         public static DataTable XlSToDataTable(string strFilePath, string strTableName,int iSheetIndex)         {              string strExtName = Path.GetExtension(strFilePath);              DataTable dt = new DataTable();             if (!string.IsNullOrEmpty(strTableName))             {                 dt.TableName = strTableName;             }              if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))             {                 using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))                 {                     HSSFWorkbook workbook = new HSSFWorkbook(file);                     ISheet sheet = workbook.GetSheetAt(iSheetIndex);                      //列头                     foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)                     {                         dt.Columns.Add(item.ToString(),typeof(string));                     }                      //写入内容                     System.Collections.IEnumerator rows = sheet.GetRowEnumerator();                     while(rows.MoveNext())                     {                         IRow row = (HSSFRow)rows.Current;                         if (row.RowNum == sheet.FirstRowNum)                         {                             continue;                         }                          DataRow dr = dt.NewRow();                         foreach (ICell item in row.Cells)                         {                             switch (item.CellType)                             {                                 case CellType.Boolean:                                     dr[item.ColumnIndex] = item.BooleanCellValue;                                     break;                                 case CellType.Error:                                     dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);                                     break;                                 case CellType.Formula:                                     switch (item.CachedFormulaResultType)                                     {                                         case CellType.Boolean:                                             dr[item.ColumnIndex] = item.BooleanCellValue;                                             break;                                         case CellType.Error:                                             dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);                                             break;                                         case CellType.Numeric:                                             if (DateUtil.IsCellDateFormatted(item))                                             {                                                 dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");                                             }                                             else                                             {                                                 dr[item.ColumnIndex] = item.NumericCellValue;                                             }                                             break;                                         case CellType.String:                                             string str = item.StringCellValue;                                             if (!string.IsNullOrEmpty(str))                                             {                                                 dr[item.ColumnIndex] = str.ToString();                                             }                                             else                                             {                                                 dr[item.ColumnIndex] = null;                                             }                                             break;                                         case CellType.Unknown:                                         case CellType.Blank:                                         default:                                             dr[item.ColumnIndex] = string.Empty;                                             break;                                     }                                     break;                                 case CellType.Numeric:                                     if (DateUtil.IsCellDateFormatted(item))                                     {                                         dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");                                     }                                     else                                     {                                         dr[item.ColumnIndex] = item.NumericCellValue;                                     }                                     break;                                 case CellType.String:                                     string strValue = item.StringCellValue;                                     if (string.IsNullOrEmpty(strValue))                                     {                                         dr[item.ColumnIndex] = strValue.ToString();                                     }                                     else                                     {                                         dr[item.ColumnIndex] = null;                                     }                                     break;                                 case CellType.Unknown:                                 case CellType.Blank:                                 default:                                     dr[item.ColumnIndex] = string.Empty;                                     break;                             }                         }                         dt.Rows.Add(dr);                     }                 }            }              return dt;         }

Datatable导出Excel的更多相关文章

  1. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  2. c# Datatable导出Excel

    using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; ...

  3. C# DataTable导出EXCEL后身份证、银行卡号等长数字信息显示乱码解决

    在DataTable导出EXCEL后发现有些格式显示有问题,比如身份证.银行卡号等大于11位的数字显示为科学计数法.13681-1等 带中划线的两段数字显示为日期格式等. 处理方法如下: public ...

  4. 【转】C# DataTable 导出 Excel 进阶 多行表头、合并单元格、中文文件名乱码

    本文原创地址:http://blog.csdn.net/ranbolwb/article/details/8083983 ,转载请保留本行. 本例子是上一篇 DataTable 导出 Excel 的进 ...

  5. DataTable 更改在有数据列的类型方法+DataTable 导出excel功能

    /// <summary> /// 导出功能 /// </summary> /// <param name="sender"></para ...

  6. C# Datatable导出Excel方法

    C# 导出Excel方法  先引用下System.IO;System.data; 具体函数如下: public static bool ExportCSV(DataTable dt, string f ...

  7. NPOI DataTable导出excel

    /// <summary> /// DataTable导出到Excel文件 /// </summary> /// <param name="dtSource&q ...

  8. WinForm 使用 NPOI 2.2.1从datatable导出Excel

    最新的NOPI应该是2.3了,但在官网上还是2.2.1. 也是第一次使用NPOI来导出Excel文件. 在写的时候搜不到2.2.1的教程,搜了一个2.2.0的教程. 不过也没什么问题,NPOI是真的方 ...

  9. 【ASP.NET】DataTable导出EXCEL,弹窗提示下载保存(完整代码)

    //新建ASPX protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); Data ...

随机推荐

  1. Hadoop 2.6.0集群搭建

    yum install gcc yum install gcc-c++ yum install make yum install autoconfautomake libtool cmake yum ...

  2. RAC_Oracle集群服务安装前期准备Prepare(案例)

    2014-07-08 Created By BaoXinjian

  3. Html滚动文字

    <marquee style="WIDTH: 388px; HEIGHT: 200px" scrollamount="2" direction=" ...

  4. Servlet3.0学习总结(二)——使用注解标注过滤器(Filter)

    Servlet3.0提供@WebFilter注解将一个实现了javax.servlet.Filter接口的类定义为过滤器,这样我们在web应用中使用过滤器时,也不再需要在web.xml文件中配置过滤器 ...

  5. 怎么安装phpcms?PHPCMS V9安装图文教程

    Phpcms是国内领先的网站内容管理系统, 同时也是一个开源的PHP开发框架.PHPCMS V9目前已提供文章.图片.下载等内容模型,在此基础上可非常方便的扩展出信息.房产.交友.点评等功能.已有的模 ...

  6. ubuntu14.04 wifi频繁掉线解决

    uname -r sudo lspci -knn sudo lshw -numeric -class network sudo ifconfig -a sudo route -nv sudo rfki ...

  7. ubuntu开机遇到-您的当前网络有.local域,我们不建议这样做而且这与AVAHI网络服务探测不兼容。该服务已被禁用

    解决 http://askubuntu.com/questions/339702/network-service-discovery-disabled-what-does-this-mean-for- ...

  8. dede织梦列表页如何调用全站子栏目

    网站原代码:{dede:channel type='son'} <a href="[field:typelink/]">[field:typename/]</a& ...

  9. 光流算法:Brox算法

    参考论文:1. High Accuracy Optical Flow Estimation Based on a Theory for Warping, Thomas Box, ECCV20042. ...

  10. POJ 3422 Kaka's Matrix Travels 【最小费用最大流】

    题意: 卡卡有一个矩阵,从左上角走到右下角,卡卡每次只能向右或者向下.矩阵里边都是不超过1000的正整数,卡卡走过的元素会变成0,问卡卡可以走k次,问卡卡最多能积累多少和. 思路: 最小费用最大流的题 ...