博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Npoi导入导出Excel操作
阅读量:6923 次
发布时间:2019-06-27

本文共 9608 字,大约阅读时间需要 32 分钟。

//Datatable导出Excelprivate 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; }        }

 

///         /// Excel文件导成Datatable        ///         /// Excel文件目录地址        /// Datatable表名        /// Excel sheet index        /// 
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; }

 

转载地址:http://nyecl.baihongyu.com/

你可能感兴趣的文章
Web缓存基础:术语、HTTP报头和缓存策略
查看>>
众包是如何解决项目开发窘境的
查看>>
怎样用 WPScan,Nmap 和 Nikto 扫描和检查一个 WordPress 站点的安全性
查看>>
GNOME Shell Seeha
查看>>
OpenAPI (Kong) Benchmark
查看>>
IT之家,这不是个案
查看>>
Oracle 高水位(HWM)标记
查看>>
文件编码
查看>>
Last_IO_Error: error connecting to master &#39;tl@192.168.199.151:3306&#39;
查看>>
kvm虚拟化学习笔记(二十)之convirt安装linux系统
查看>>
Babel 入门教程
查看>>
Objective-C中的老板是这样发通知的(Notification)
查看>>
HTTP协议及其POST与GET操作差异 & C#中如何使用POST、GET等
查看>>
解决FragmentTabHost切换标题栏变更问题
查看>>
讨喜的隔离可变性(十一)调和类型化角色
查看>>
如何使用枚举的组合值
查看>>
为什么线程安全的ACE容器不支持[]操作符
查看>>
为iPhone 6设计自适应布局
查看>>
如何通过固定的IP访问阿里云OSS的文件
查看>>
【索引】反向索引--条件 范围查询
查看>>