由于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 私有方法 /// <summary>
/// 获取要保存的文件名称(含完整路径)
/// </summary>
/// <returns></returns>
private static string GetSaveFilePath()
{
SaveFileDialog saveFileDig = new SaveFileDialog();
saveFileDig.Filter = "Excel Office97-2003(*.xls)|.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";
saveFileDig.FilterIndex = ;
saveFileDig.OverwritePrompt = true;
saveFileDig.InitialDirectory = Common.DesktopDirectory;
string filePath = null;
if (saveFileDig.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDig.FileName;
} return filePath;
} /// <summary>
/// 判断是否为兼容模式
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool GetIsCompatible(string filePath)
{
return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
} /// <summary>
/// 创建工作薄
/// </summary>
/// <param name="isCompatible"></param>
/// <returns></returns>
private static IWorkbook CreateWorkbook(bool isCompatible)
{
if (isCompatible)
{
return new HSSFWorkbook();
}
else
{
return new XSSFWorkbook();
}
} /// <summary>
/// 创建工作薄(依据文件流)
/// </summary>
/// <param name="isCompatible"></param>
/// <param name="stream"></param>
/// <returns></returns>
private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
{
if (isCompatible)
{
return new HSSFWorkbook(stream);
}
else
{
return new XSSFWorkbook(stream);
}
} /// <summary>
/// 创建表格头单元格
/// </summary>
/// <param name="sheet"></param>
/// <returns></returns>
private static ICellStyle GetCellStyle(IWorkbook workbook)
{
ICellStyle style = workbook.CreateCellStyle();
style.FillPattern = FillPattern.SolidForeground;
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; return style;
} /// <summary>
/// 从工作表中生成DataTable
/// </summary>
/// <param name="sheet"></param>
/// <param name="headerRowIndex"></param>
/// <returns></returns>
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 + ;
break;
}
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
} for (int i = (headerRowIndex + ); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i); if (row != null && !string.IsNullOrEmpty(row.Cells[].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 公共导出方法 /// <summary>
/// 由DataSet导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <returns>Excel工作表</returns>
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 = ; i < sourceDs.Tables.Count; i++)
{
DataTable table = sourceDs.Tables[i];
string sheetName = "result" + i.ToString();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow headerRow = sheet.CreateRow();
// 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 = ; 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; } /// <summary>
/// 由DataTable导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <returns>Excel工作表</returns>
public static string ExportToExcel(DataTable sourceTable, string sheetName = "result", string filePath = null)
{
if (sourceTable.Rows.Count <= ) 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();
// 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 = ; 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;
} /// <summary>
/// 由List导出Excel
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="data">在导出的List</param>
/// <param name="sheetName">sheet名称</param>
/// <returns></returns>
public static string ExportToExcel<T>(List<T> data, IList<KeyValuePair<string, string>> headerNameList, string sheetName = "result", string filePath = null) where T : class
{
if (data.Count <= ) 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(); for (int i = ; i < headerNameList.Count; i++)
{
ICell cell = headerRow.CreateCell(i);
cell.SetCellValue(headerNameList[i].Value);
cell.CellStyle = cellStyle;
} Type t = typeof(T);
int rowIndex = ;
foreach (T item in data)
{
IRow dataRow = sheet.CreateRow(rowIndex);
for (int n = ; 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;
} /// <summary>
/// 由DataGridView导出
/// </summary>
/// <param name="grid"></param>
/// <param name="sheetName"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null)
{
if (grid.Rows.Count <= ) 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(); for (int i = ; i < grid.Columns.Count; i++)
{
ICell cell = headerRow.CreateCell(i);
cell.SetCellValue(grid.Columns[i].Name);
cell.CellStyle = cellStyle;
} int rowIndex = ;
foreach (DataGridViewRow row in grid.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
for (int n = ; 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 公共导入方法 /// <summary>
/// 由Excel导入DataTable
/// </summary>
/// <param name="excelFileStream">Excel文件流</param>
/// <param name="sheetName">Excel工作表名称</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <param name="isCompatible">是否为兼容模式</param>
/// <returns>DataTable</returns>
public static DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible)
{
IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
ISheet sheet = null;
int sheetIndex = -;
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;
} /// <summary>
/// 由Excel导入DataTable
/// </summary>
/// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
/// <param name="sheetName">Excel工作表名称</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <returns>DataTable</returns>
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);
}
} /// <summary>
/// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable
/// </summary>
/// <param name="excelFileStream">Excel文件流</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <param name="isCompatible">是否为兼容模式</param>
/// <returns>DataSet</returns>
public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible)
{
DataSet ds = new DataSet();
IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
for (int i = ; i < workbook.NumberOfSheets; i++)
{
ISheet sheet = workbook.GetSheetAt(i);
DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);
ds.Tables.Add(table);
} excelFileStream.Close();
workbook = null; return ds;
} /// <summary>
/// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable
/// </summary>
/// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <returns>DataSet</returns>
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 公共转换方法 /// <summary>
/// 将Excel的列索引转换为列名,列索引从0开始,列名从A开始。如第0列为A,第1列为B...
/// </summary>
/// <param name="index">列索引</param>
/// <returns>列名,如第0列为A,第1列为B...</returns>
public static string ConvertColumnIndexToColumnName(int index)
{
index = index + ;
int system = ;
char[] digArray = new char[];
int i = ;
while (index > )
{
int mod = index % system;
if (mod == ) mod = system;
digArray[i++] = (char)(mod - + 'A');
index = (index - ) / ;
}
StringBuilder sb = new StringBuilder(i);
for (int j = i - ; j >= ; j--)
{
sb.Append(digArray[j]);
}
return sb.ToString();
} /// <summary>
/// 转化日期
/// </summary>
/// <param name="date">日期</param>
/// <returns></returns>
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[]);
int month = Convert.ToInt32(time[]);
int day = Convert.ToInt32(time[]);
string years = Convert.ToString(year);
string months = Convert.ToString(month);
string days = Convert.ToString(day);
if (months.Length == )
{
dt = Convert.ToDateTime(date);
}
else
{
string rq = "";
if (years.Length == )
{
years = "" + years;
}
if (months.Length == )
{
months = "" + months;
}
if (days.Length == )
{
days = "" + days;
}
rq = "" + years + "-" + months + "-" + days;
dt = Convert.ToDateTime(rq);
}
}
catch
{
throw new Exception("日期格式不正确,转换日期失败!");
}
return dt;
} /// <summary>
/// 转化数字
/// </summary>
/// <param name="d">数字字符串</param>
/// <returns></returns>
public static decimal ConvertDecimal(object d)
{
string dStr = (d ?? "").ToString();
decimal result = ;
if (decimal.TryParse(dStr, out result))
{
return result;
}
else
{
throw new Exception("数字格式不正确,转换数字失败!");
} } #endregion
}
}

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

NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中的更多相关文章

  1. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  2. MVC NPOI Linq导出Excel通用类

    之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = , ...

  3. NPOI导入导出Excel工具类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Ref ...

  4. NPOI导入导出Excel

    .net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交  代码:  第一步. 在页面里面加入2个隐藏的iframe, 如下 ...

  5. .Net core NPOI导入导出Excel

    最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...

  6. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  7. NPOI MVC 模型导出Excel通用类

    通用类: public enum DataTypeEnum { Int = , Float = , Double = , String = , DateTime = , Date = } public ...

  8. Npoi导入导出Excel操作

    之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...

  9. NPOI 导入导出excel 支持 03 07

    因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps.但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上 ...

随机推荐

  1. SpringMVC中的自定义参数绑定案例

    由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型.所以需要自定义参数绑定.前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适 ...

  2. 转:C# 小数位数保留的方法集锦

    转载自:http://www.jb51.net/article/17010.htm 1. System.Globalization.NumberFormatInfo provider = new Sy ...

  3. golang学习笔记18 用go语言编写移动端sdk和app开发gomobile

    golang学习笔记18 用go语言编写移动端sdk和app开发gomobile gomobile的使用-用go语言编写移动端sdk和app开发https://blog.csdn.net/u01249 ...

  4. Mybatis+MySQL动态分页查询

    https://blog.csdn.net/qq_34137397/article/details/63289621 mybatis有两种分页方法 1.内存分页,也就是假分页.本质是查出所有的数据然后 ...

  5. Step4:SQL Server 跨网段(跨机房)复制

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 解决方案(Solution) 搭建过程(Process) 注意事项(Attention) 参考 ...

  6. Autel MaxiSys Elite Diagnostic Tool Common problem solving methods

    1. updating MaxiFlash Elite to firmware 3.21? My maxisys communicate with the MaxiFlash J2534 but Ma ...

  7. 在vim编辑器python实现tab补全功能

    在vim编辑器中实现python tab补全插件有Pydiction,Pydiction可以实现下面python代码的自动补全: 1. 简单python关键词补全 2. python函数补全带括号 3 ...

  8. Inferred type 'S' for type parameter 'S' is not within its bound;

    在使用springboot 方法报错: Inferred type 'S' for type parameter 'S' is not within its bound; should extends ...

  9. 怎样从外网访问内网Lighttpd?

    本地安装了一个Lighttpd,只能在局域网内访问,怎样从外网也能访问到本地的Lighttpd呢?本文将介绍具体的实现步骤. 准备工作 安装并启动Lighttpd 默认安装的Lighttpd端口是80 ...

  10. 注册页面的JSON响应方式详细分析(与前端页面交互方式之一)

    控制器层 需求分析: 访问路径:`/user/reg.do` //自己根据功能需求设定的请求参数:`username=xx&password=xx&&phone=xx& ...