博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中
阅读量:7288 次
发布时间:2019-06-30

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

由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案。

注意:若直接使用在WinForm项目中,必需先下载并在项目中引用NPOI2.0或以上版本的组件才可以正常使用。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Data;using System.Windows.Forms;using NPOI.SS.UserModel;using NPOI.HSSF.UserModel;using NPOI.XSSF.UserModel;using Zwj.TEMS.Common;namespace TEMS.Service{    public static class ExcelHelperForCs    {        #region 私有方法        ///         /// 获取要保存的文件名称(含完整路径)        ///         /// 
private static string GetSaveFilePath() { SaveFileDialog saveFileDig = new SaveFileDialog(); saveFileDig.Filter = "Excel Office97-2003(*.xls)|.xls|Excel Office2007及以上(*.xlsx)|*.xlsx"; saveFileDig.FilterIndex = 0; saveFileDig.OverwritePrompt = true; saveFileDig.InitialDirectory = Common.DesktopDirectory; string filePath = null; if (saveFileDig.ShowDialog() == DialogResult.OK) { filePath = saveFileDig.FileName; } return filePath; } /// /// 判断是否为兼容模式 /// /// ///
private static bool GetIsCompatible(string filePath) { return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase); } /// /// 创建工作薄 /// /// ///
private static IWorkbook CreateWorkbook(bool isCompatible) { if (isCompatible) { return new HSSFWorkbook(); } else { return new XSSFWorkbook(); } } /// /// 创建工作薄(依据文件流) /// /// /// ///
private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream) { if (isCompatible) { return new HSSFWorkbook(stream); } else { return new XSSFWorkbook(stream); } } /// /// 创建表格头单元格 /// /// ///
private static ICellStyle GetCellStyle(IWorkbook workbook) { ICellStyle style = workbook.CreateCellStyle(); style.FillPattern = FillPattern.SolidForeground; style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; return style; } /// /// 从工作表中生成DataTable /// /// /// ///
private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex) { DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "") { // 如果遇到第一个空列,则不再继续向后读取 cellCount = i + 1; break; } DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row != null && !string.IsNullOrEmpty(row.Cells[0].StringCellValue)) { DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = row.GetCell(j).ToString(); } } table.Rows.Add(dataRow); } } return table; } #endregion #region 公共导出方法 /// /// 由DataSet导出Excel /// /// 要导出数据的DataTable ///
Excel工作表
public static string ExportToExcel(DataSet sourceDs, string filePath = null) { if (string.IsNullOrEmpty(filePath)) { filePath = GetSaveFilePath(); } if (string.IsNullOrEmpty(filePath)) return null; bool isCompatible = GetIsCompatible(filePath); IWorkbook workbook = CreateWorkbook(isCompatible); ICellStyle cellStyle = GetCellStyle(workbook); for (int i = 0; i < sourceDs.Tables.Count; i++) { DataTable table = sourceDs.Tables[i]; string sheetName = "result" + i.ToString(); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); // handling header. foreach (DataColumn column in table.Columns) { ICell cell = headerRow.CreateCell(column.Ordinal); cell.SetCellValue(column.ColumnName); cell.CellStyle = cellStyle; } // handling value. int rowIndex = 1; foreach (DataRow row in table.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in table.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString()); } rowIndex++; } } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); workbook.Write(fs); fs.Dispose(); workbook = null; return filePath; } /// /// 由DataTable导出Excel /// /// 要导出数据的DataTable ///
Excel工作表
public static string ExportToExcel(DataTable sourceTable, string sheetName = "result", string filePath = null) { if (sourceTable.Rows.Count <= 0) return null; if (string.IsNullOrEmpty(filePath)) { filePath = GetSaveFilePath(); } if (string.IsNullOrEmpty(filePath)) return null; bool isCompatible = GetIsCompatible(filePath); IWorkbook workbook = CreateWorkbook(isCompatible); ICellStyle cellStyle = GetCellStyle(workbook); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); // handling header. foreach (DataColumn column in sourceTable.Columns) { ICell headerCell = headerRow.CreateCell(column.Ordinal); headerCell.SetCellValue(column.ColumnName); headerCell.CellStyle = cellStyle; } // handling value. int rowIndex = 1; foreach (DataRow row in sourceTable.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in sourceTable.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue((row[column]??"").ToString()); } rowIndex++; } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); workbook.Write(fs); fs.Dispose(); sheet = null; headerRow = null; workbook = null; return filePath; } /// /// 由List导出Excel /// ///
类型
/// 在导出的List /// sheet名称 ///
public static string ExportToExcel
(List
data, IList
> headerNameList, string sheetName = "result", string filePath = null) where T : class { if (data.Count <= 0) return null; if (string.IsNullOrEmpty(filePath)) { filePath = GetSaveFilePath(); } if (string.IsNullOrEmpty(filePath)) return null; bool isCompatible = GetIsCompatible(filePath); IWorkbook workbook = CreateWorkbook(isCompatible); ICellStyle cellStyle = GetCellStyle(workbook); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); for (int i = 0; i < headerNameList.Count; i++) { ICell cell = headerRow.CreateCell(i); cell.SetCellValue(headerNameList[i].Value); cell.CellStyle = cellStyle; } Type t = typeof(T); int rowIndex = 1; foreach (T item in data) { IRow dataRow = sheet.CreateRow(rowIndex); for (int n = 0; n < headerNameList.Count; n++) { object pValue = t.GetProperty(headerNameList[n].Key).GetValue(item, null); dataRow.CreateCell(n).SetCellValue((pValue ?? "").ToString()); } rowIndex++; } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); workbook.Write(fs); fs.Dispose(); sheet = null; headerRow = null; workbook = null; return filePath; } ///
/// 由DataGridView导出 /// ///
///
///
///
public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null) { if (grid.Rows.Count <= 0) return null; if (string.IsNullOrEmpty(filePath)) { filePath = GetSaveFilePath(); } if (string.IsNullOrEmpty(filePath)) return null; bool isCompatible = GetIsCompatible(filePath); IWorkbook workbook = CreateWorkbook(isCompatible); ICellStyle cellStyle = GetCellStyle(workbook); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); for (int i = 0; i < grid.Columns.Count; i++) { ICell cell = headerRow.CreateCell(i); cell.SetCellValue(grid.Columns[i].Name); cell.CellStyle = cellStyle; } int rowIndex = 1; foreach (DataGridViewRow row in grid.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); for (int n = 0; n < grid.Columns.Count; n++) { dataRow.CreateCell(n).SetCellValue((row.Cells[n].Value ?? "").ToString()); } rowIndex++; } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); workbook.Write(fs); fs.Dispose(); sheet = null; headerRow = null; workbook = null; return filePath; } #endregion #region 公共导入方法 ///
/// 由Excel导入DataTable /// ///
Excel文件流 ///
Excel工作表名称 ///
Excel表头行索引 ///
是否为兼容模式 ///
DataTable
public static DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible) { IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream); ISheet sheet = null; int sheetIndex = -1; if (int.TryParse(sheetName, out sheetIndex)) { sheet = workbook.GetSheetAt(sheetIndex); } else { sheet = workbook.GetSheet(sheetName); } DataTable table = GetDataTableFromSheet(sheet, headerRowIndex); excelFileStream.Close(); workbook = null; sheet = null; return table; } ///
/// 由Excel导入DataTable /// ///
Excel文件路径,为物理路径。 ///
Excel工作表名称 ///
Excel表头行索引 ///
DataTable
public static DataTable ImportFromExcel(string excelFilePath, string sheetName, int headerRowIndex) { using (FileStream stream = System.IO.File.OpenRead(excelFilePath)) { bool isCompatible = GetIsCompatible(excelFilePath); return ImportFromExcel(stream, sheetName, headerRowIndex, isCompatible); } } ///
/// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable /// ///
Excel文件流 ///
Excel表头行索引 ///
是否为兼容模式 ///
DataSet
public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible) { DataSet ds = new DataSet(); IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream); for (int i = 0; i < workbook.NumberOfSheets; i++) { ISheet sheet = workbook.GetSheetAt(i); DataTable table = GetDataTableFromSheet(sheet, headerRowIndex); ds.Tables.Add(table); } excelFileStream.Close(); workbook = null; return ds; } ///
/// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable /// ///
Excel文件路径,为物理路径。 ///
Excel表头行索引 ///
DataSet
public static DataSet ImportFromExcel(string excelFilePath, int headerRowIndex) { using (FileStream stream = System.IO.File.OpenRead(excelFilePath)) { bool isCompatible = GetIsCompatible(excelFilePath); return ImportFromExcel(stream, headerRowIndex, isCompatible); } } #endregion #region 公共转换方法 ///
/// 将Excel的列索引转换为列名,列索引从0开始,列名从A开始。如第0列为A,第1列为B... /// ///
列索引 ///
列名,如第0列为A,第1列为B...
public static string ConvertColumnIndexToColumnName(int index) { index = index + 1; int system = 26; char[] digArray = new char[100]; int i = 0; while (index > 0) { int mod = index % system; if (mod == 0) mod = system; digArray[i++] = (char)(mod - 1 + 'A'); index = (index - 1) / 26; } StringBuilder sb = new StringBuilder(i); for (int j = i - 1; j >= 0; j--) { sb.Append(digArray[j]); } return sb.ToString(); } ///
/// 转化日期 /// ///
日期 ///
public static DateTime ConvertDate(object date) { string dtStr = (date ?? "").ToString(); DateTime dt = new DateTime(); if (DateTime.TryParse(dtStr, out dt)) { return dt; } try { string spStr = ""; if (dtStr.Contains("-")) { spStr = "-"; } else if (dtStr.Contains("/")) { spStr = "/"; } string[] time = dtStr.Split(spStr.ToCharArray()); int year = Convert.ToInt32(time[2]); int month = Convert.ToInt32(time[0]); int day = Convert.ToInt32(time[1]); string years = Convert.ToString(year); string months = Convert.ToString(month); string days = Convert.ToString(day); if (months.Length == 4) { dt = Convert.ToDateTime(date); } else { string rq = ""; if (years.Length == 1) { years = "0" + years; } if (months.Length == 1) { months = "0" + months; } if (days.Length == 1) { days = "0" + days; } rq = "20" + years + "-" + months + "-" + days; dt = Convert.ToDateTime(rq); } } catch { throw new Exception("日期格式不正确,转换日期失败!"); } return dt; } ///
/// 转化数字 /// ///
数字字符串 ///
public static decimal ConvertDecimal(object d) { string dStr = (d ?? "").ToString(); decimal result = 0; if (decimal.TryParse(dStr, out result)) { return result; } else { throw new Exception("数字格式不正确,转换数字失败!"); } } #endregion }}

 

原文:https://www.cnblogs.com/jimcsharp/p/6634530.html

 

你可能感兴趣的文章
五虎遁月 和 五鼠遁时 法
查看>>
很好的一个blog,记录一下
查看>>
关于mysql修复表
查看>>
DBWn与物理写
查看>>
ajax实现的动态展开
查看>>
python 与数据结构
查看>>
LAMP搭建2:Apache安装
查看>>
linux之正则表达式和grep
查看>>
示例演示“距离矢量路由算法”工作原理
查看>>
mysql replication支持ssl,一主一从 +CA服务器
查看>>
mybatis源码总结
查看>>
机器学习理论篇1:机器学习的数学基础
查看>>
Python 守护进程
查看>>
七牛云王珂 直播分享 | 如何快速搭建智能化的统一日志管理系统
查看>>
BusyBox
查看>>
configure make make install in linux
查看>>
剑指offer:调整数组顺序使奇数位于偶数前面
查看>>
一步一步学Silverlight 2系列(3):界面布局
查看>>
本人部分博客导航(ing...)
查看>>
redis环境搭建笔记
查看>>