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.Web;
namespace PortalPBIRS.Models
{
class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
readonly int EXCEL03_MaxRow = 65535;
public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
/// <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)
{
int k = 0, cellCount = 0;
IRow firstRow = sheet.GetRow(0);//获取第一行
while (firstRow == null)
{
firstRow = sheet.GetRow(++k);//排除空行,找到第一个有字符的行
}
if (isFirstRowColumn)//第一行是列名
{
cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = "";
if (cell.CellType == CellType.Formula)
{
cellValue = cell.RichStringCellValue.String;
}
else
{
cellValue = cell.StringCellValue;
}
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue.Replace("
",""));
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else// 第一行不是列名
{
int max = 0;
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)// 找到所有行中最多字符
{
if (sheet.GetRow(i) == null)
continue;
max = (sheet.GetRow(i).LastCellNum > max) ? sheet.GetRow(i).LastCellNum : max;
}
cellCount = max;
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
DataColumn column = new DataColumn();
data.Columns.Add(column);
}
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)//将从文件中获取的数据存储到DataTable中
{
IRow row = sheet.GetRow(i);
if (row == null)
{
continue; //没有数据的行默认是null
}
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
//同理,没有数据的单元格都默认是null
if (row.GetCell(j) != null)
{
if (row.GetCell(j).CellType == CellType.Formula)
{
row.GetCell(j).SetCellType(CellType.String);
dataRow[j]= row.GetCell(j).RichStringCellValue.String;
}
else
{
dataRow[j] = row.GetCell(j).ToString();
}
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
/// <summary>
/// 将DataTable转换为excel2003格式。
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public byte[] DataTableToExcel(DataTable dt, string sheetName)
{
IWorkbook book = new HSSFWorkbook();
if (dt.Rows.Count < EXCEL03_MaxRow)
DataWrite2Sheet(dt, 0, dt.Rows.Count - 1, book, sheetName);
else
{
int page = dt.Rows.Count / EXCEL03_MaxRow;
for (int i = 0; i < page; i++)
{
int start = i * EXCEL03_MaxRow;
int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - 1;
DataWrite2Sheet(dt, start, end, book, sheetName + i.ToString());
}
int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow;
DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, lastPageItemCount, book, sheetName + page.ToString());
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
return ms.ToArray();
}
private void DataWrite2Sheet(DataTable dt, int startRow, int endRow, IWorkbook book, string sheetName)
{
ISheet sheet = book.CreateSheet(sheetName);
IRow header = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = header.CreateCell(i);
string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName;
cell.SetCellValue(val);
}
int rowIndex = 1;
for (int i = startRow; i <= endRow; i++)
{
DataRow dtRow = dt.Rows[i];
IRow excelRow = sheet.CreateRow(rowIndex++);
for (int j = 0; j < dtRow.ItemArray.Length; j++)
{
excelRow.CreateCell(j).SetCellValue(dtRow[j].ToString());
}
}
}
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;
}
}
}
}