简介
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。
代码封装
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace Genersoft.GS.ZDB.Development.Controller.RO
{
public class NPOIHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public NPOIHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
#region 导出Excel 根据datatable的格式导出对应的格式
/// <summary>
/// 导出Excel 根据datatable的格式导出对应的格式
/// </summary>
/// <param name="fileName">保存路径</param>
/// <param name="dtSource">导出的数据源</param>
/// <param name="sheetName">创建的sheet表名称</param>
/// <param name="isColumnWritten">是否写入列名作为Excel头</param>
/// <returns></returns>
public int DataTableToExcel( DataTable dtSource, string sheetName, bool isColumnWritten)
{
FileStream fs = null;
int i = 0;
int j = 0;
int count = 0;
IWorkbook workbook = null;
ISheet sheet = null;
try
{
using (fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy/mm/dd");
ICellStyle dateStyleStr = workbook.CreateCellStyle();
IDataFormat formatStr = workbook.CreateDataFormat();
dateStyleStr.DataFormat = formatStr.GetFormat("@");
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < dtSource.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(dtSource.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
foreach (DataRow dr in dtSource.Rows)
{
IRow row = sheet.CreateRow(count);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = row.CreateCell(column.Ordinal);
string drValue = dr[column].ToString();
switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
newCell.SetCellType(CellType.String);
newCell.CellStyle = dateStyleStr;
break;
case "System.DateTime"://日期类型
DateTime dateV;
if (!string.IsNullOrEmpty(drValue))
{
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);
newCell.SetCellType(CellType.Boolean);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
if (!string.IsNullOrEmpty(drValue))
{
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
newCell.SetCellType(CellType.Numeric);
}
break;
case "System.Decimal"://浮点型
case "System.Double":
if (!string.IsNullOrEmpty(drValue))
{
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
newCell.SetCellType(CellType.Numeric);
}
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
++count;
}
for ( i = 0; i <= sheet.LastRowNum; i++)
{
sheet.AutoSizeColumn(i,true);
}
sheet.SetColumnWidth(4, 10 * 256);
sheet.SetColumnWidth(5, 10 * 256);
if (dtSource.Columns.Count >= 13)
{
sheet.SetColumnWidth(13, 10 * 256);
}
workbook.Write(fs); //写入到excel}
return count;
}
}
catch (Exception ex)
{
fs.Dispose();
fs.Close();
throw;
}
}
#endregion
#region 导出Excel 根据datatable的格式导出对应的格式
/// <summary>
/// 导出Excel 根据datatable的格式导出对应的格式
/// </summary>
/// <param name="fileName">保存路径</param>
/// <param name="dtSource">导出的数据源</param>
/// <param name="sheetName">创建的sheet表名称</param>
/// <param name="isColumnWritten">是否写入列名作为Excel头</param>
/// <returns></returns>
public int DataTableToExcelString(DataTable dtSource, string sheetName, bool isColumnWritten)
{
FileStream fs = null;
int i = 0;
int j = 0;
int count = 0;
IWorkbook workbook = null;
ISheet sheet = null;
try
{
using (fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy/mm/dd hh:mm:ss");
ICellStyle dateStyleStr = workbook.CreateCellStyle();
IDataFormat formatStr = workbook.CreateDataFormat();
dateStyleStr.DataFormat = formatStr.GetFormat("@");
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < dtSource.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(dtSource.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
foreach (DataRow dr in dtSource.Rows)
{
IRow row = sheet.CreateRow(count);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = row.CreateCell(column.Ordinal);
string drValue = dr[column].ToString();
switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
newCell.CellStyle = dateStyleStr;
break;
case "System.DateTime"://日期类型
DateTime dateV;
if (!string.IsNullOrEmpty(drValue))
{
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":
if (!string.IsNullOrEmpty(drValue))
{
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
newCell.SetCellType(CellType.Numeric);
}
break;
case "System.Decimal"://浮点型
case "System.Double":
if (!string.IsNullOrEmpty(drValue))
{
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
newCell.SetCellType(CellType.Numeric);
}
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
++count;
}
for (i = 0; i < sheet.LastRowNum; i++)
{
sheet.AutoSizeColumn(i, true);
}
workbook.Write(fs); //写入到excel}
return count;
}
}
catch (Exception ex)
{
fs.Dispose();
fs.Close();
throw;
}
}
#endregion
#region 将excel中的数据导入到DataTable中
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
throw;
}
}
#endregion
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}
呵呵呵呵哒
呵呵呵呵哒
呵呵呵呵哒
呵呵呵呵哒
回复就可以看到
正在找呢