public class NPOIHelper
{
public static void WriteDataToExceel(string fileName, DataSet ds)
{
if (File.Exists(fileName))
throw new Exception("File is Exists!");
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
try
{
IWorkbook workbook = ReadToWorkBook(ds, fileName);
workbook.Write(stream);
}
catch (Exception exception)
{
throw exception;
}
}
} public static void WriteDataToExceel(string fileName, DataTable dt)
{
if (File.Exists(fileName))
throw new Exception("File is Exists!");
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
try
{
IWorkbook workbook = ReadToWorkBook(dt, fileName);
workbook.Write(stream);
}
catch (Exception exception)
{
throw exception;
}
}
} public static MemoryStream WriteDataToExcel(DataSet ds, string Extension = ".xls")
{
MemoryStream memoryStream = new MemoryStream();
try
{
IWorkbook workbook = ReadToWorkBook(ds, Extension);
workbook.Write(memoryStream); workbook = null;
}
catch (Exception exception)
{
throw exception;
}
return memoryStream;
} private static IWorkbook ReadToWorkBook(DataSet ds, string Extension)
{
IWorkbook workbook = null;
if (Extension.ToLower().EndsWith(".xls"))
workbook = new HSSFWorkbook();
else
workbook = new XSSFWorkbook();
foreach (DataTable table in ds.Tables)
{
ISheet sheet = workbook.CreateSheet(table.TableName);
IRow headerRow = sheet.CreateRow(0);
foreach (DataColumn column in table.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
int rowIndex = 1;
foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
DateTime temp = DateTime.Now;
foreach (DataColumn column in table.Columns)
{
if (DateTime.TryParse(row[column].ToString(),out temp))
{
dataRow.CreateCell(column.Ordinal).SetCellValue(temp.ToString("yyyy-MM-dd"));
}
else
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
sheet.SetColumnWidth(column.Ordinal, 4000);
}
rowIndex++;
}
sheet = null;
headerRow = null;
} return workbook;
} private static IWorkbook ReadToWorkBook(DataTable dt, string Extension)
{
IWorkbook workbook = null;
if (Extension.ToLower().EndsWith(".xls"))
workbook = new HSSFWorkbook();
else
workbook = new XSSFWorkbook();
//foreach (DataTable table in ds.Tables)
//{
ISheet sheet = workbook.CreateSheet(dt.TableName);
IRow headerRow = sheet.CreateRow(0);
foreach (DataColumn column in dt.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
int rowIndex = 1;
foreach (DataRow row in dt.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dt.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} rowIndex++;
}
sheet = null;
headerRow = null;
// } return workbook;
} public static DataSet ExcelToDataSet(string excelPath)
{
return ExcelToDataSet(excelPath, true);
}
public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
{
int sheetCount;
try
{
return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
}
catch
{
return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount, true);
}
} public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount, bool isXlsx = false)
{
using (DataSet ds = new DataSet())
{
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook;
IFormulaEvaluator evaluator;
GetWorkBook(excelPath, fileStream, out workbook, out evaluator, isXlsx);
sheetCount = workbook.NumberOfSheets;
for (int i = 0; i < sheetCount; ++i)
{
DataTable dt = ExcelToDataTable(workbook.GetSheetAt(i), evaluator, firstRowAsHeader);
ds.Tables.Add(dt);
}
return ds;
}
}
} public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader = true)
{
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook;
IFormulaEvaluator evaluator;
GetWorkBook(excelPath, fileStream, out workbook, out evaluator);
return ExcelToDataTable(workbook.GetSheet(sheetName), evaluator, firstRowAsHeader);
}
} public static DataTable ExcelToDataTable(string excelPath, int pageIndex,Stream stream, bool firstRowAsHeader = true)
{
using (Stream fileStream = stream)
{
IWorkbook workbook;
IFormulaEvaluator evaluator;
GetWorkBook(excelPath, fileStream, out workbook, out evaluator);
return ExcelToDataTable(workbook.GetSheetAt(pageIndex), evaluator, firstRowAsHeader);
}
} public static DataTable ExcelToDataTable(string excelPath, int pageIndex, bool firstRowAsHeader = true)
{
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook;
IFormulaEvaluator evaluator;
GetWorkBook(excelPath, fileStream, out workbook, out evaluator);
if (pageIndex > workbook.NumberOfSheets)
throw new Exception("参数PageIndex>Excel页面总数!");
return ExcelToDataTable(workbook.GetSheetAt(pageIndex), evaluator, firstRowAsHeader);
}
} private static void GetWorkBook(string excelPath, FileStream fileStream, out IWorkbook workbook, out IFormulaEvaluator evaluator, bool isUseXlsx = false)
{
workbook = null;
evaluator = null;
if (excelPath.ToLower().EndsWith(".xls") && !isUseXlsx)
{
workbook = new HSSFWorkbook(fileStream, true);
evaluator = new HSSFFormulaEvaluator(workbook);
}
else
{
workbook = new XSSFWorkbook(fileStream);
evaluator = new XSSFFormulaEvaluator(workbook);
}
} private static void GetWorkBook(string excelPath, Stream fileStream, out IWorkbook workbook, out IFormulaEvaluator evaluator, bool isUseXlsx = false)
{
workbook = null;
evaluator = null;
if (excelPath.ToLower().EndsWith(".xls") && !isUseXlsx)
{
workbook = new HSSFWorkbook(fileStream, true);
evaluator = new HSSFFormulaEvaluator(workbook);
}
else
{
workbook = new XSSFWorkbook(fileStream);
evaluator = new XSSFFormulaEvaluator(workbook);
}
} #region 内部方法
private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader)
{
if (firstRowAsHeader)
{
return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
}
else
{
return ExcelToDataTable(sheet, evaluator);
}
}
private static DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
IRow firstRow = sheet.GetRow(0) as IRow;
int cellCount = GetCellCount(sheet);
for (int i = 0; i < cellCount; i++)
{
if (firstRow.GetCell(i) != null)
{
dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string));
}
else
{
dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
}
}
for (int i = 1; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i) as IRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRow(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
if (sheet.LastRowNum != 0)
{
int cellCount = GetCellCount(sheet);
for (int i = 0; i < cellCount; i++)
{
dt.Columns.Add(string.Format("F{0}", i), typeof(string));
}
for (int i = 0; i < sheet.FirstRowNum; ++i)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
} for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i) as IRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRow(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static void FillDataRowByHSSFRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr)
{
if (row != null)
{
for (int j = 0; j < dr.Table.Columns.Count; j++)
{
ICell cell = row.GetCell(j) as ICell;
if (cell != null)
{
switch (cell.CellType)
{
case CellType.Blank:
dr[j] = DBNull.Value;
break;
case CellType.Boolean:
dr[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
dr[j] = cell.DateCellValue;
else
dr[j] = cell.NumericCellValue;
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Error:
dr[j] = cell.ErrorCellValue;
break;
case CellType.Formula:
cell = evaluator.EvaluateInCell(cell) as ICell;
dr[j] = cell.ToString();
break;
default:
throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
}
}
}
}
}
private static int GetCellCount(ISheet sheet)
{
int firstRowNum = sheet.FirstRowNum;
int cellCount = 0;
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
{
IRow row = sheet.GetRow(i) as IRow;
if (row != null && row.LastCellNum > cellCount)
{
cellCount = row.LastCellNum;
}
}
return cellCount;
} #endregion #region 用于Web导出
/// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">文件名</param>
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
{
HttpContext curContext = HttpContext.Current;
try
{
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
curContext.Response.End();
}
catch (Exception e)
{ throw;
} }
#endregion #region DataTable导出到Excel的MemoryStream
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
public static MemoryStream Export(DataTable dtSource, string strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(); #region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
/* si.Author = "文件作者信息"; //填加xls文件作者信息
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息
si.Subject = "主题信息";//填加文件主题信息*/
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet();
} #region 表头及样式
{
IRow headerRow = sheet.CreateRow(0);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText); ICellStyle headStyle = workbook.CreateCellStyle();
// headStyle.Alignment = HorizontalAlignment.CENTER;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
//headerRow.Dispose();
}
#endregion #region 列头及样式
{
IRow headerRow = sheet.CreateRow(1);
ICellStyle headStyle = workbook.CreateCellStyle();
// headStyle.Alignment = HorizontalAlignment.CENTER;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
headStyle.SetFont(font);
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
//headerRow.Dispose();
}
#endregion rowIndex = 2;
}
#endregion #region 填充内容
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
} }
#endregion rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
}
#endregion }

  

NPOIHelper的更多相关文章

  1. 分享一个前辈的NPOIhelper

    即拿即用: 首先要下载npoi的dll,此不赘述,接着添加引用: using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel ...

  2. NPOIHelper.cs (NPOI 2.1.1)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  3. C#利用NPOI处理excel的类 NPOIHelper.cs

    个人的NPOIHelp类,包括datatable导出到excel,dataset导出到excel,excel导入到datatable,excel导入到dataset, 更新excel中的数据,验证导入 ...

  4. 基于NPOI的Excel数据导入

    从Excel导入数据最令人头疼的是数据格式的兼容性,特别是日期类型的兼容性.为了能够无脑导入日期,折腾了一天的NPOI.在经过测试确实可以导入任意格式的合法日期后,写下这篇小文,与大家共享.完整代码请 ...

  5. 基于NPOI导出和导入Excel

    概述 NPOI,顾名思义,就是POI的.NET版本.NPOI就是用.NET语言编写的一套数据导出Excel的开源项目,支持XML.xls.xlsx.ppt等格式..NET不仅实现Excel导出还可以实 ...

  6. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

  7. npoi批量导入实现及相关技巧

    批量导入功能对于大部分后台系统来说都是不可或缺的一部分,常见的场景-基础数据的录入(部门,用户),用批量导入方便快捷.最近项目需要用到批量导入,决定花点时间写套比较通用的Excel导入功能.经过考虑, ...

  8. Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行

    Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行 模版格式,图格式是最简单的格式,但实际效果不是这种,实际效果图如图2 图2 ,注意看红色部分,一对一是正常的,但是有一对多的订单 ...

  9. [Solution] NPOI操作Excel

    NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...

随机推荐

  1. esrdtfyghjk

    两融余额止跌回升,金融股回落飘绿,千股涨停续演,沪指收复4000点未果涨逾2% 相关报道 [今日收盘]灾后重建激情抢筹 大盘两日反弹500点 [今日收盘]沪指涨近6%重回3700点 未停牌个股九成涨停 ...

  2. Hello Point——WebGL

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  3. linux sed的使用

    sed是一个很好的文件处理工具,本身是一个管道命令,主要是以行为单位进行处理, 可以将数据行进行替换.删除.新增.选取等特定工作. sed本质上是一个编辑器,但是它是非交互式的,这点与VIM不同:同时 ...

  4. 无后台的网站 内容暂存json

    当网站无后台时,将数据暂存储为json文档,然后通过调用json文件获取数据填充前端页面 存储json格式的文件 [ { "id": 1, "cat": &qu ...

  5. servlet/jsp详解

    首先谈servlet的简单定义,servlet其实就是一门web服务器端编程的技术. servlet它分两种,一种是servlet容器,所有的servlet对象都要放在servlet容器中才能被调用执 ...

  6. ajax 选项卡

    Ajax其实就是交互式网页应用开发技术包括以下几个方面: 1.XHTML和CSS 2.使用DOM作为动态显示和交互 3.使用XML和XSLT 做数据交互和操作 (这些完全不太懂) 4.使用XMLHtt ...

  7. 开启Java博客

    已经转Java大半年了,Java知识都来自于工作,没有一个系统的学习,所以这一个多月我都在看Java的一些基本东西,准备系统性的学习下Java知识.这一个多月看的也挺多,从servlet,jsp,st ...

  8. HTML CSS中比较重要的

    在网页中有了HTML和CSS之后,我们还需要学会布局,我们可以将整个网页看做是一个DIV,然后将所有内容放入到这个DIV中. 内容中的每一块我们都可以用DIV包起来,我们将这个DIV看做一个盒子,然后 ...

  9. python线程池(threadpool)模块使用笔记

    一.安装与简介 pip install threadpool pool = ThreadPool(poolsize) requests = makeRequests(some_callable, li ...

  10. MapReduce job.setNumReduceTasks(0)思考

    一.概述 在 http://zy19982004.iteye.com/blog/2037549的最后曾经提到过,这里再详细探讨一下. 二.job.setNumReduceTasks(0)唯一影响的是m ...