using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;
using System.Collections;
using System.Text.RegularExpressions;
using System.Xml;
namespace Util
{
public class ExcelHelper
{
private IWorkbook _workbook;
public bool AutoColumnHeder;
public FileStream fileStream;
public ExcelHelper(string _excelFielPath)
{
this.AutoColumnHeder = true;
this.initHSSFWorkbook(_excelFielPath);
}
public ExcelHelper(string _excelFielPath, bool _autoColumnHeder)
{
this.AutoColumnHeder = true;
this.initHSSFWorkbook(_excelFielPath);
this.AutoColumnHeder = _autoColumnHeder;
}
public ExcelHelper(string _excelFielPath, string sheetName)
{
this.AutoColumnHeder = true;
this.initHSSFWorkbook(_excelFielPath);
if (!this.IsExistExcelTableName(sheetName))
{
throw new Exception("指定的模板格式不正确,请选择正确的EXCEL模板");
}
}
public void Dispose()
{
if (this.fileStream != null)
{
this.fileStream.Close();
this.fileStream.Dispose();
}
}
public DataSet ExcelToDataSet()
{
DataSet set = new DataSet();
List<string> excelTablesName = this.GetExcelTablesName();
foreach (string str in excelTablesName)
{
set.Tables.Add(this.ExcelToDataTable(str));
}
return set;
}
public DataTable ExcelToDataTable(int index)
{
ISheet sheetAt = this._workbook.GetSheetAt(index);
return this.ExcelToDataTable(sheetAt, 0);
}
public DataTable ExcelToDataTable(string tName)
{
ISheet sheet = this._workbook.GetSheet(tName);
return this.ExcelToDataTable(sheet, 0);
}
private DataTable ExcelToDataTable(ISheet sheet, int headerIndex)
{
if (sheet.LastRowNum < headerIndex)
{
throw new Exception("Excel模板格式不对,读取下标值错误");
}
DataTable table = new DataTable();
IRow row = sheet.GetRow(headerIndex);
int lastCellNum = row.LastCellNum;
for (int i = 0; i < lastCellNum; i++)
{
string columnName = string.Empty;
if (this.AutoColumnHeder)
{
columnName = Convert.ToChar(0x41) + i.ToString();
}
else
{
columnName = row.GetCell(i).ToString();
}
table.Columns.Add(columnName);
}
IEnumerator rowEnumerator = sheet.GetRowEnumerator();
if (!this.AutoColumnHeder)
{
rowEnumerator.MoveNext();
}
while (rowEnumerator.MoveNext())
{
IRow current = (IRow)rowEnumerator.Current;
DataRow row3 = table.NewRow();
for (int j = 0; j < lastCellNum; j++)
{
ICell cell = current.GetCell(j);
if (cell == null || cell.ToString().Trim() == "")
{
row3[j] = System.DBNull.Value;
}
else
{
if (cell.CellType == CellType.NUMERIC && HSSFDateUtil.IsCellDateFormatted(cell))
{
row3[j] = HSSFDateUtil.GetJavaDate(cell.NumericCellValue).ToString("yyyy-MM-dd");
}
else
{
row3[j] = cell;
}
}
}
table.Rows.Add(row3);
}
return table;
}
public DataTable ExcelToDataTable(string tName, int headerIndex)
{
ISheet sheet = this._workbook.GetSheet(tName);
return this.ExcelToDataTable(sheet, headerIndex);
}
public static MemoryStream Export(DataTable dtSource)
{
IWorkbook workbook = new HSSFWorkbook();
string sheetname = "Sheet1";
if (!string.IsNullOrEmpty(dtSource.TableName))
{
sheetname = dtSource.TableName;
}
ISheet sheet = workbook.CreateSheet(sheetname);
IRow row = sheet.CreateRow(0);
IFont font = workbook.CreateFont();
font.FontName = "宋体";
foreach (DataColumn column in dtSource.Columns)
{
row.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
ICellStyle dateFormat = GetDateFormat(workbook);
int rownum = 1;
foreach (DataRow row2 in dtSource.Rows)
{
IRow row3 = sheet.CreateRow(rownum);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = row3.CreateCell(column.Ordinal);
HorizontalAlignment ha = HorizontalAlignment.CENTER;//水平对齐
SetCellValue(row2[column].ToString(), dateFormat,font,ha, column.DataType, newCell);
}
rownum++;
}
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
stream.Flush();
stream.Position = 0L;
return stream;
}
}
public static void Export(DataTable dtSource, string strFileName)
{
using (MemoryStream stream = Export(dtSource))
{
using (FileStream stream2 = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] buffer = stream.ToArray();
stream2.Write(buffer, 0, buffer.Length);
stream2.Flush();
}
}
}
public static MemoryStream Export<T>(IList<T> list,XmlNodeList xnlColMapp) where T : class
{
IWorkbook workbook = new HSSFWorkbook();
string sheetname = "Sheet1";
ISheet sheet = workbook.CreateSheet(sheetname);
IRow row = sheet.CreateRow(0);
IFont font = workbook.CreateFont();
font.FontName = "宋体";
int colOrdinal = 0;//列的序号
foreach (XmlNode xn in xnlColMapp)
{
string headname = xn.Attributes["column"].Value;//单元格头部名称
row.CreateCell(colOrdinal).SetCellValue(headname);
colOrdinal++;
}
Type it = list.First().GetType();
ICellStyle dateFormat = GetDateFormat(workbook);
int rownum = 1;
foreach (T t in list)
{
if (t == null)
{
continue;
}
IRow row3 = sheet.CreateRow(rownum);
colOrdinal = 0;
foreach (XmlNode xn in xnlColMapp)
{
string propName = xn.Attributes["property"].Value;
object cellVal;
if (propName != "")
{
System.Reflection.PropertyInfo pi = it.GetProperty(propName);
cellVal = pi.GetValue(t, null);
ICell newCell = row3.CreateCell(colOrdinal);
HorizontalAlignment ha = HorizontalAlignment.CENTER;
if (cellVal==null)
newCell.SetCellValue("");
else
SetCellValue(cellVal + "", dateFormat,font,ha, cellVal.GetType(), newCell);
colOrdinal++;
}
}
//foreach (DataColumn column in dtSource.Columns)
//{
// ICell newCell = row3.CreateCell(column.Ordinal);
// SetCellValue(row2[column].ToString(), dateFormat, column, newCell);
//}
rownum++;
}
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
stream.Flush();
stream.Position = 0L;
return stream;
}
}
public static void Export<T>(IList<T> list, string strFileName,XmlNodeList xnlMapp) where T : class
{
using (MemoryStream stream = Export<T>(list, xnlMapp))
{
using (FileStream stream2 = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] buffer = stream.ToArray();
stream2.Write(buffer, 0, buffer.Length);
stream2.Flush();
}
}
}
~ExcelHelper()
{
if (this.fileStream != null)
{
this.fileStream.Close();
this.fileStream.Dispose();
}
}
private static ICellStyle GetDateFormat(IWorkbook workbook)
{
ICellStyle style = workbook.CreateCellStyle();
style.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy-mm-dd");
return style;
}
public void GetExcelObj(Action<object> act)
{
act(this._workbook);
this.Dispose();
}
public List<string> GetExcelTablesName()
{
List<string> list = new List<string>();
foreach (ISheet sheet in this._workbook)
{
list.Add(sheet.SheetName);
}
return list;
}
private void initHSSFWorkbook(string _excelFielPath)
{
if (string.IsNullOrEmpty(_excelFielPath))
{
throw new Exception("Excel文件路径不能为空!");
}
if (!File.Exists(_excelFielPath))
{
throw new Exception("指定路径的Excel文件不存在!");
}
string str = Path.GetExtension(_excelFielPath).ToLower();
using (this.fileStream = new FileStream(_excelFielPath, FileMode.Open, FileAccess.Read))
{
this._workbook = WorkbookFactory.Create(this.fileStream);
}
}
public bool IsExistExcelTableName(string tName)
{
return this.GetExcelTablesName().Contains(tName);
}
private static void SetCellValue(string drValue, ICellStyle dateStyle,IFont font,HorizontalAlignment ha, Type columnType, ICell newCell)
{
switch (columnType.ToString())
{
case "System.String":
newCell.SetCellValue(drValue);
break;
case "System.DateTime":
DateTime time;
DateTime.TryParse(drValue, out time);
newCell.SetCellValue(time);
newCell.CellStyle = dateStyle;
break;
case "System.Boolean":
{
bool result = false;
bool.TryParse(drValue, out result);
newCell.SetCellValue(result);
break;
}
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
{
int num = 0;
int.TryParse(drValue, out num);
newCell.SetCellValue((double)num);
break;
}
case "System.Decimal":
case "System.Double":
{
double num2 = 0.0;
double.TryParse(drValue, out num2);
newCell.SetCellValue(num2);
break;
}
case "System.DBNull":
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
newCell.CellStyle.Alignment = ha;//水平对齐
newCell.CellStyle.SetFont(font);//设置字体
}
}
}
生成Excel调用方法:
/// <summary>
/// 生成指定接口的Excel文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="lt">数据源</param>
/// <param name="filePath">生成的文件路径</param>
/// <param name="fileID">接口ID(属性与列映射用)</param>
public static void ExportExcel<T>(IList<T> lt, string filePath,string fileID) where T: class
{
StringBuilder builder = new StringBuilder();
string path = filePath;
Type it = lt.First().GetType();
XmlDocument doc = new XmlDocument();
string mapFile = System.Web.HttpContext.Current.Server.MapPath("~/Config/OuterPack/FileMap.xml");
doc.Load(mapFile);
string xPath = string.Format("//FileMap[@id='{0}']/Mapping", fileID);
XmlNodeList nlist= doc.SelectNodes(xPath);
EnsureFile(path);
ExcelHelper.Export<T>(lt, filePath, nlist);
return;
}
<?xml version="1.0" encoding="utf-8" ?>
<Root>
<FileMap id="shilexls">
<Mapping property="RowNo" column="No"/>
<Mapping property="Policy_No" column="Policy_no"/>
<Mapping property="Owner_Name" column="Policy Holder"/>
<Mapping property="Calender_Year" column="Calender Year"/>
<Mapping property="Issue_Month" column="Issue Month"/>
<Mapping property="Issue_Day" column="Issue Day"/>
<Mapping property="Campaign_Name" column="Campaign Name"/>
<Mapping property="Sponsor_Code" column="Sponsor"/>
<Mapping property="Package_Code" column="Package Code"/>
<Mapping property="Branch_Code" column="Camp_branch"/>
<Mapping property="Campaign_Code" column="Campaign"/>
<Mapping property="Channel_Code" column="Channel"/>
<Mapping property="Address1" column="Address1"/>
<Mapping property="Post_code" column="Post_code"/>
<Mapping property="Mobile_Phone_No" column="Policy Holder Mobile Phone No"/>
<Mapping property="SumPrem" column="Total Insurance Amount"/>
<Mapping property="Payment_Period" column="Payment Period"/>
</FileMap>
</Root>
读取方法:
/// <summary>
/// 读取Excel文件
/// </summary>
/// <param name="filePath">文件名(含详细地址)</param>
/// <param name="extensionName">文件的后缀名</param>
/// <param name="sheetName">表名</param>
/// <returns></returns>
public DataTable ReadExcelFile(string filePath, string extensionName, string sheetName)
{
try
{
ExcelHelper excelHelper = new ExcelHelper(filePath);
excelHelper.AutoColumnHeder = false;
return excelHelper.ExcelToDataTable(0);
}
catch (Exception ex)
{
throw ex;
}
}