ComplianceServer/oldcode/WebHelper/ExcelHelper.cs

1311 lines
56 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using WX.CRM.Common;
namespace WX.CRM.WebHelper
{
public class ExcelHelper
{
#region Excel
public static Stream ExportListObjectToExcel<T>(List<T> obj, string fieldName, string sheetName, DataFormart func)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
// handling header.
// handling value.
int sheetSize = 65535;
int sheetCout = (obj.Count / sheetSize) + 1;//获取一个工作簿中多少页
for (int i = 0; i < sheetCout; i++)
{
ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue(fieldName);
int rowIndex = 1;
int mcount = (i + 1) * sheetSize > obj.Count ? obj.Count : (i + 1) * sheetSize;
for (int m = (i * sheetSize); m < mcount; m++)
{
IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.CreateCell(0).SetCellValue(string.Format("{0}", obj[m]));
rowIndex++;
}
}
//foreach (object row in obj)
//{
// IRow dataRow = sheet.CreateRow(rowIndex);
// dataRow.CreateCell(0).SetCellValue(string.Format("{0}", row));
// rowIndex++;
//}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
workbook = null;
return ms;
}
#endregion
#region List反射导出Excel
/// <summary>
/// List反射导出Excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listModel">实体列表</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="sheetSize">一个工作簿的数据量不能超过65536</param>
/// <returns>返回一个流</returns>
public static Stream ExportListModelToExcel<T>(List<T> listModel, string sheetName, int sheetSize, DataFormart func)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
string columnName = string.Empty;
int x = 0;
DisplayNameAttribute attribute = null;
if (sheetSize > 65536)
sheetSize = 65536;
int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页
for (int i = 0; i < sheetCout; i++)
{
ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
IRow headerRow = sheet.CreateRow(0);
// 设置表头.
x = 0;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute));
headerRow.CreateCell(x).SetCellValue(attribute == null ? info.Name : attribute.DisplayName);//获取类中的DisplayName属性
x++;
}
// 绑定值
int rowIndex = 1;
int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize;
for (int m = (i * sheetSize); m < mcount; m++)
{
x = 0;
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (PropertyInfo column in listModel[m].GetType().GetProperties())
{
//dataRow.CreateCell(x).SetCellValue(string.Format("{0}", column.GetValue(listModel[m], null)));
if (func == null)
{
//dataRow.CreateCell(x).SetCellValue(string.Format("{0}", column.GetValue(listModel[m], null)));
ICell icell = dataRow.CreateCell(x);
ICellValeSet(column.PropertyType.FullName, string.Format("{0}", column.GetValue(listModel[m], null)), icell);
}
else
dataRow.CreateCell(x).SetCellValue(func(column.Name, column.GetValue(listModel[m], null)));//委托处理
x++;
}
rowIndex++;
}
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
workbook = null;
return ms;
}
#endregion
#region List反射导出Excel
public delegate string DataFormart(string key, object value);
private static string entrySpace = "WX.CRM.Model.Entity";//嵌套实体的命名空间
/// <summary>
/// List反射导出Excel根据以选择的字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listModel">实体列表</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="sheetSize">一个工作簿的数据量不能超过65536</param>
/// <param name="checkedFilds">已经选择的字段</param>
/// <returns>返回一个流</returns>
public static Stream ExportListModelToExcel<T>(List<T> listModel, string sheetName, int sheetSize, string checkedFilds, DataFormart func)
{
checkedFilds = checkedFilds.ToUpper();
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
string columnName = string.Empty;
int x = 0;
DisplayNameAttribute attribute = null;
if (sheetSize > 65536)
sheetSize = 65536;
int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页
for (int i = 0; i < sheetCout; i++)
{
ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
IRow headerRow = sheet.CreateRow(0);
// 设置表头.
x = 0;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
if (info.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象
{
foreach (PropertyInfo childInfo in info.PropertyType.GetProperties())
{
if (checkedFilds.IndexOf("[" + childInfo.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续
continue;
attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(childInfo, typeof(DisplayNameAttribute));
headerRow.CreateCell(x).SetCellValue(attribute == null ? childInfo.Name : attribute.DisplayName);//获取类中的DisplayName属性
x++;
}
}
else
{
if (checkedFilds.IndexOf("[" + info.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续
continue;
attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute));
headerRow.CreateCell(x).SetCellValue(attribute == null ? info.Name : attribute.DisplayName);//获取类中的DisplayName属性
x++;
}
}
// 绑定值
int rowIndex = 1;
int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize;
for (int m = (i * sheetSize); m < mcount; m++)
{
x = 0;
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (PropertyInfo column in listModel[m].GetType().GetProperties())
{
if (column.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象
{
foreach (PropertyInfo childColumn in column.PropertyType.GetProperties())
{
if (checkedFilds.IndexOf("[" + childColumn.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续
continue;
if (func == null)
{
ICell icell = dataRow.CreateCell(x);
ICellValeSet(childColumn.PropertyType.FullName, string.Format("{0}", childColumn.GetValue(column.GetValue(listModel[m], null), null)), icell);
}
else
dataRow.CreateCell(x).SetCellValue(func(childColumn.Name, childColumn.GetValue(column.GetValue(listModel[m], null), null)));//委托处理
x++;
}
}
else
{
if (checkedFilds.IndexOf("[" + column.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续
continue;
if (func == null)
{
ICell icell = dataRow.CreateCell(x);
ICellValeSet(column.PropertyType.FullName, string.Format("{0}", column.GetValue(listModel[m], null)), icell);
}
else
dataRow.CreateCell(x).SetCellValue(func(column.Name, column.GetValue(listModel[m], null)));//委托处理
x++;
}
}
rowIndex++;
}
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
workbook = null;
return ms;
}
/// <summary>
/// List反射导出Excel根据以选择的字段顺序按照checkedFilds顺序类型按照数据类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listModel">实体列表</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="sheetSize">一个工作簿的数据量不能超过65536</param>
/// <param name="checkedFilds">已经选择的字段</param>
/// <param name="checkedTtile">已经选择的字段 中文名称</param>
/// <returns>返回一个流</returns>
public static Stream ExportListModelToExcel<T>(List<T> listModel, string sheetName, int sheetSize, string checkedFilds, string checkedTtile, DataFormart func)
{
checkedFilds = checkedFilds.ToUpper();
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
string columnName = string.Empty;
int x = 0;
if (sheetSize > 65536)
sheetSize = 65536;
int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页
Dictionary<string, string> fildAndTitle = new Dictionary<string, string>();//存储字段和中文标题
string[] dataTitle = checkedTtile.Split(',');
checkedFilds = checkedFilds.Replace("[", "");
checkedFilds = checkedFilds.Length > 0 ? checkedFilds.Substring(0, checkedFilds.Length - 1) : checkedFilds;
string[] dataFilds = checkedFilds.Split(']');
try
{
for (int i = 0; i < dataFilds.Length; i++)
{
string fild = dataFilds[i].Trim();
string title = dataTitle[i].Trim();
if (fild != "")
{
fildAndTitle.Add(fild, title);
}
}
//--------------------------------先获取所有数据----------------------------------------
List<Dictionary<string, ExcelCell>> allData = new List<Dictionary<string, ExcelCell>>();
ExcelCell cell = null;
string filedName = string.Empty;
for (int i = 0; i < listModel.Count; i++)
{
Dictionary<string, ExcelCell> row = new Dictionary<string, ExcelCell>();
foreach (PropertyInfo column in listModel[i].GetType().GetProperties())
{
if (column.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象
{
foreach (PropertyInfo childColumn in column.PropertyType.GetProperties())
{
filedName = childColumn.Name.ToUpper();
if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续
continue;
cell = new ExcelCell();
if (func == null)
cell.nvalue = string.Format("{0}", childColumn.GetValue(column.GetValue(listModel[i], null), null));
else
cell.nvalue = func(childColumn.Name, childColumn.GetValue(column.GetValue(listModel[i], null), null));//委托处理
cell.type = childColumn.PropertyType.FullName;
cell.fild = filedName;
cell.title = fildAndTitle[filedName];
if (row.ContainsKey(filedName))
continue;
row.Add(childColumn.Name.ToUpper(), cell);
}
}
else
{
filedName = column.Name.ToUpper();
if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续
continue;
cell = new ExcelCell();
if (func == null)
cell.nvalue = string.Format("{0}", column.GetValue(listModel[i], null));
else
cell.nvalue = func(column.Name, column.GetValue(listModel[i], null));//委托处理
cell.type = column.PropertyType.FullName;
cell.fild = filedName;
cell.title = fildAndTitle[filedName];
if (row.ContainsKey(filedName))
continue;
row.Add(filedName, cell);
}
}
allData.Add(row);
}
//-----------------------------------end---------------------------------------
//-----------------------------------生成excel---------------------------------
//ICellStyle dateStyle = Getcellstyle(workbook, stylexls.时间);
//ICellStyle numberStyle = Getcellstyle(workbook, stylexls.数字);
for (int i = 0; i < sheetCout; i++)
{
ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
IRow headerRow = sheet.CreateRow(0);
// 设置表头.
x = 0;
foreach (string title in dataTitle)
{
headerRow.CreateCell(x).SetCellValue(title);
x++;
}
// 绑定值
int rowIndex = 1;
int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize;
for (int m = (i * sheetSize); m < mcount; m++)
{
x = 0;
IRow dataRow = sheet.CreateRow(rowIndex);
Dictionary<string, ExcelCell> row = allData[m];
foreach (string fild in dataFilds)
{
cell = row[fild];
ICell icell = dataRow.CreateCell(x);
//icell.CellStyle = Getcellstyle(workbook, GetCellType(cell.type));
//if (cell.type.IndexOf("System.Demail") > -1 || cell.type.IndexOf("System.Int") > -1)
//{
// Double doub;
// if (Double.TryParse(cell.nvalue, out doub))
// {
// icell.CellStyle = numberStyle;
// }
// icell.SetCellValue(cell.nvalue);
//}
//else if (cell.type.IndexOf("System.DateTime") > -1)
//{
// DateTime dt;
// if (DateTime.TryParse(cell.nvalue, out dt))
// {
// icell.CellStyle = dateStyle;
// }
// icell.SetCellValue(cell.nvalue);
//}
//else
ICellValeSet(cell, icell);
//icell.SetCellValue(cell.nvalue);
x++;
}
rowIndex++;
}
}
}
catch (Exception ex) { LogHelper.Error("excel导出失败" + ex.ToString()); }
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
workbook = null;
return ms;
}
private static void ICellValeSet(string dbType, string dbValue, ICell icell)
{
switch (GetCellType(dbType))
{
case stylexls.:
int wovalue = 0;
if (int.TryParse(dbValue, out wovalue))
{
icell.SetCellValue(wovalue);
}
else
{
icell.SetCellValue(dbValue);
}
break;
case stylexls.:
double dobValue = 0;
if (double.TryParse(dbValue, out dobValue))
{
icell.SetCellValue(dobValue);
}
else
{
icell.SetCellValue(dbValue);
}
break;
case stylexls.:
DateTime timeValue;
if (DateTime.TryParse(dbValue, out timeValue))
{
icell.SetCellValue(timeValue.ToString("yyyy/MM/dd HH:mm:ss"));
}
else
{
icell.SetCellValue("");
}
break;
case stylexls.: icell.SetCellValue(dbValue.ToString()); break;
}
}
private static void ICellValeSet(ExcelCell cell, ICell icell)
{
switch (GetCellType(cell.type))
{
case stylexls.:
int wovalue = 0;
if (int.TryParse(cell.nvalue, out wovalue))
{
icell.SetCellValue(wovalue);
}
else
{
icell.SetCellValue(cell.nvalue);
}
break;
case stylexls.:
double dobValue = 0;
if (double.TryParse(cell.nvalue, out dobValue))
{
icell.SetCellValue(dobValue);
}
else
{
icell.SetCellValue(cell.nvalue);
}
break;
case stylexls.:
DateTime timeValue;
if (DateTime.TryParse(cell.nvalue, out timeValue))
{
icell.SetCellValue(timeValue.ToString("yyyy/MM/dd HH:mm:ss"));
}
else
{
icell.SetCellValue("");
}
break;
case stylexls.: icell.SetCellValue(cell.nvalue.ToString()); break;
}
}
private static stylexls GetCellType(string fullTypeName)
{
if (fullTypeName == null)
return stylexls.;
if (fullTypeName.IndexOf("System.Decimal") > -1)
return stylexls.;
if (fullTypeName.IndexOf("System.Int") > -1)
return stylexls.;
if (fullTypeName.IndexOf("System.DateTime") > -1)
return stylexls.;
return stylexls.;
}
#endregion
#region DataSet导出Excel
/// <summary>
/// 由DataSet导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <param name="sheetName">工作表名称</param>
/// <returns>Excel工作表</returns>
public static Stream ExportDataSetToExcel(DataSet sourceDs, string sheetName)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
int sheetSize = 65535;
int allcount = sourceDs.Tables[0].Rows.Count;
int sheetCout = (allcount / sheetSize) + 1;//获取一个工作簿中多少页
//for (int i = 0; i < sheetCout; i++)
//{
// ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
// IRow headerRow = sheet.CreateRow(0);
// headerRow.CreateCell(0).SetCellValue(fieldName);
// int rowIndex = 1;
// int mcount = (i + 1) * sheetSize > obj.Count ? obj.Count : (i + 1) * sheetSize;
// for (int m = (i * sheetSize); m < mcount; m++)
// {
// IRow dataRow = sheet.CreateRow(rowIndex);
// dataRow.CreateCell(0).SetCellValue(string.Format("{0}", obj[m]));
// rowIndex++;
// }
//}
//string[] sheetNames = sheetName.Split(',');
for (int i = 0; i < sheetCout; i++)
{
ISheet sheet = workbook.CreateSheet(sheetName + (i + 1));
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in sourceDs.Tables[0].Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
// handling value.
int rowIndex = 1;
int mcount = (i + 1) * sheetSize > allcount ? allcount : (i + 1) * sheetSize;
for (int m = (i * sheetSize); m < mcount; m++)
{
IRow dataRow = sheet.CreateRow(rowIndex);
DataRow row = sourceDs.Tables[0].Rows[m];
foreach (DataColumn column in sourceDs.Tables[0].Columns)
{
ICell icell = dataRow.CreateCell(column.Ordinal);
ICellValeSet(column.DataType.FullName, row[column].ToString(), icell);
//dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
//foreach (DataRow row in sourceDs.Tables[i].Rows)
//{
// IRow dataRow = sheet.CreateRow(rowIndex);
// foreach (DataColumn column in sourceDs.Tables[i].Columns)
// {
// ICell icell = dataRow.CreateCell(column.Ordinal);
// ICellValeSet(column.DataType.FullName, row[column].ToString(), icell);
// //dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
// }
// rowIndex++;
//}
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
workbook = null;
return ms;
}
/// <summary>
/// 由DataSet导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <param name="fileName">指定Excel工作表名称</param>
/// <returns>Excel工作表</returns>
public static void ExportDataSetToExcel(DataSet sourceDs, string fileName, string sheetName)
{
MemoryStream ms = ExportDataSetToExcel(sourceDs, sheetName) as MemoryStream;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
ms.Close();
ms = null;
}
/// <summary>
/// 由DataTable导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <returns>Excel工作表</returns>
public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in sourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
// handling value.
int rowIndex = 1;
foreach (DataRow row in sourceTable.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in sourceTable.Columns)
{
ICell icell = dataRow.CreateCell(column.Ordinal);
ICellValeSet(column.DataType.FullName, row[column].ToString(), icell);
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
workbook = null;
return ms;
}
/// <summary>
/// 头部委托函数(可以自己定义重写excle的头部)
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public delegate string HeadFormart(string key);
/// <summary>
/// datable导出excle
/// </summary>
/// <param name="sourceTable">DataTable数据源</param>
/// <param name="sheetName">工作簿名称</param>
/// <param name="checkedFilds">被选中的字段</param>
/// <param name="head">excle头部格式化委托</param>
/// <param name="func">数据格式委托</param>
/// <returns></returns>
public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName, string checkedFilds, string checkedTtile, DataFormart func)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow headerRow = sheet.CreateRow(0);
checkedFilds = checkedFilds.ToLower();
// handling header.
checkedFilds = checkedFilds.ToUpper();
Dictionary<string, string> fildAndTitle = new Dictionary<string, string>();//存储字段和中文标题
string[] dataTitle = checkedTtile.Split(',');
checkedFilds = checkedFilds.Replace("[", "");
checkedFilds = checkedFilds.Length > 0 ? checkedFilds.Substring(0, checkedFilds.Length - 1) : checkedFilds;
string[] dataFilds = checkedFilds.Split(']');
int cellIndex = 0;
try
{
for (int i = 0; i < dataFilds.Length; i++)
{
string fild = dataFilds[i].Trim();
string title = dataTitle[i].Trim();
if (fild != "" && !fildAndTitle.ContainsKey(fild))
{
fildAndTitle.Add(fild, title);
}
}
//--------------------------------先获取所有数据----------------------------------------
List<Dictionary<string, ExcelCell>> allData = new List<Dictionary<string, ExcelCell>>();
ExcelCell cell = null;
string filedName = string.Empty;
for (int i = 0; i < sourceTable.Rows.Count; i++)
{
Dictionary<string, ExcelCell> row = new Dictionary<string, ExcelCell>();
foreach (DataColumn column in sourceTable.Columns)
{
filedName = column.ColumnName.ToUpper();
if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续
continue;
cell = new ExcelCell();
if (func == null)
cell.nvalue = string.Format("{0}", sourceTable.Rows[i][column].ToString());
else
cell.nvalue = func(column.ColumnName, sourceTable.Rows[i][column]);//委托处理
cell.fild = filedName;
cell.type = column.DataType.FullName;
cell.title = fildAndTitle[filedName];
row.Add(filedName, cell);
}
allData.Add(row);
}
//-----------------------------------end---------------------------------------
//---------------------------------设置头部------------------------------------
foreach (string title in dataTitle)//根据传过来的 标题生成excel标题
{
headerRow.CreateCell(cellIndex).SetCellValue(title);
cellIndex++;
}
//----------------------------------end----------------------------------------
//-------------------------------循环设置数据----------------------------------
int rowIndex = 1;
foreach (Dictionary<string, ExcelCell> row in allData)
{
cellIndex = 0;
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (string fild in dataFilds)
{
if (!row.ContainsKey(fild))
continue;
cell = row[fild];
ICell icell = dataRow.CreateCell(cellIndex);
ICellValeSet(cell, icell);
//icell.SetCellValue(cell.nvalue);
cellIndex++;
}
rowIndex++;
}
}
catch (Exception ex) { LogHelper.Error("excel导出失败" + ex.ToString()); }
//---------------------------------end----------------------------------------
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
workbook = null;
return ms;
}
/// <summary>
/// datable导出excle
/// </summary>
/// <param name="sourceTable">DataTable数据源</param>
/// <param name="sheetName">工作簿名称</param>
/// <param name="checkedFilds">被选中的字段</param>
/// <param name="head">excle头部格式化委托</param>
/// <param name="func">数据格式委托</param>
/// <returns></returns>
public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName, string checkedFilds, HeadFormart head, DataFormart func)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow headerRow = sheet.CreateRow(0);
checkedFilds = checkedFilds.ToLower();
// handling header.
int cellIndex = 0;
foreach (DataColumn column in sourceTable.Columns)
{
if (checkedFilds.IndexOf("[" + column.ColumnName.ToLower() + "]") > -1)//字段是否被选择
{
if (head != null)
headerRow.CreateCell(cellIndex).SetCellValue(head(column.ColumnName));
else
headerRow.CreateCell(cellIndex).SetCellValue(column.ColumnName);
cellIndex++;
}
}
// handling value.
int rowIndex = 1;
foreach (DataRow row in sourceTable.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
cellIndex = 0;
foreach (DataColumn column in sourceTable.Columns)
{
if (checkedFilds.IndexOf("[" + column.ColumnName.ToLower() + "]") > -1)//字段是否被选择
{
if (func != null)
{
dataRow.CreateCell(cellIndex).SetCellValue(func(column.ColumnName, row[column].ToString()));
}
else
{
ICell icell = dataRow.CreateCell(cellIndex);
ICellValeSet(column.DataType.FullName, row[column].ToString(), icell);
//dataRow.CreateCell(cellIndex).SetCellValue(row[column].ToString());
}
cellIndex++;
}
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
workbook = null;
return ms;
}
/// <summary>
/// 由DataTable导出Excel
/// </summary>
/// <param name="sourceTable">要导出数据的DataTable</param>
/// <param name="fileName">指定Excel工作表名称</param>
/// <returns>Excel工作表</returns>
public static void ExportDataTableToExcel(DataTable sourceTable, string fileName, string sheetName)
{
MemoryStream ms = ExportDataTableToExcel(sourceTable, sheetName) as MemoryStream;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
ms.Close();
ms = null;
}
#endregion
#region Render导出Excel
/// <summary>
///由Render导出Excel
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(IDataReader reader)
{
MemoryStream ms = new MemoryStream();
using (reader)
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow headerRow = sheet.CreateRow(0);
int cellCount = reader.FieldCount;
// handling header.
for (int i = 0; i < cellCount; i++)
{
headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
}
// handling value.
int rowIndex = 1;
while (reader.Read())
{
IRow dataRow = sheet.CreateRow(rowIndex);
for (int i = 0; i < cellCount; i++)
{
dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}
return ms;
}
#endregion
#region Excel导入DataTable
/// <summary>
/// 由Excel导入DataTable
/// </summary>
/// <param name="excelFileStream">Excel文件流</param>
/// <param name="sheetName">Excel工作表名称</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <returns>DataTable</returns>
public static DataTable ImportDataTableFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
{
HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
ISheet sheet = workbook.GetSheet(sheetName);
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
dataRow[j] = string.Format("{0}", row.GetCell(j));
table.Rows.Add(dataRow);
}
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 ImportDataTableFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
{
using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
{
return ImportDataTableFromExcel(stream, sheetName, headerRowIndex);
}
}
/// <summary>
/// 由Excel导入DataTable
/// </summary>
/// <param name="excelFileStream">Excel文件流</param>
/// <param name="sheetName">Excel工作表索引</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <returns>DataTable</returns>
public static DataTable ImportDataTableFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
{
HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
ISheet sheet = workbook.GetSheetAt(sheetIndex);
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 + 1;
break;
}
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
{
// 如果遇到第一个空行,则不再继续向后读取
break;
}
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
dataRow[j] = row.GetCell(j);
}
table.Rows.Add(dataRow);
}
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 ImportDataTableFromExcel(string excelFilePath, int sheetIndex, int headerRowIndex)
{
using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
{
return ImportDataTableFromExcel(stream, sheetIndex, headerRowIndex);
}
}
#endregion
#region Excel导入DataSetDataTable
/// <summary>
/// 由Excel导入DataSet如果有多个工作表则导入多个DataTable
/// </summary>
/// <param name="excelFileStream">Excel文件流</param>
/// <param name="headerRowIndex">Excel表头行索引</param>
/// <returns>DataSet</returns>
public static DataSet ImportDataSetFromExcel(Stream excelFileStream, int headerRowIndex)
{
DataSet ds = new DataSet();
HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
for (int a = 0, b = workbook.NumberOfSheets; a < b; a++)
{
ISheet sheet = workbook.GetSheetAt(a);
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 + 1;
break;
}
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
{
// 如果遇到第一个空行,则不再继续向后读取
break;
}
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);
}
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 ImportDataSetFromExcel(string excelFilePath, int headerRowIndex)
{
using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
{
return ImportDataSetFromExcel(stream, headerRowIndex);
}
}
#endregion
#region
/// <summary>
/// 获取字体样式
/// </summary>
/// <param name="hssfworkbook">Excel操作类</param>
/// <param name="fontname">字体名</param>
/// <param name="fontcolor">字体颜色</param>
/// <param name="fontsize">字体大小</param>
/// <returns></returns>
public static IFont GetFontStyle(HSSFWorkbook hssfworkbook, string fontfamily, HSSFColor fontcolor, int fontsize)
{
IFont font1 = hssfworkbook.CreateFont();
if (string.IsNullOrEmpty(fontfamily))
{
font1.FontName = fontfamily;
}
if (fontcolor != null)
{
font1.Color = fontcolor.Indexed;
}
font1.IsItalic = true;
font1.FontHeightInPoints = (short)fontsize;
return font1;
}
#endregion
#region
// <summary>
/// 获取单元格样式
/// </summary>
/// <param name="hssfworkbook">Excel操作类</param>
/// <param name="font">单元格字体</param>
/// <param name="fillForegroundColor">图案的颜色</param>
/// <param name="fillPattern">图案样式</param>
/// <param name="fillBackgroundColor">单元格背景</param>
/// <param name="ha">垂直对齐方式</param>
/// <param name="va">垂直对齐方式</param>
/// <returns></returns>
public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, IFont font, HSSFColor fillForegroundColor, FillPattern fillPattern, HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va)
{
ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
cellstyle.FillPattern = fillPattern;
cellstyle.Alignment = ha;
cellstyle.VerticalAlignment = va;
if (fillForegroundColor != null)
{
cellstyle.FillForegroundColor = fillForegroundColor.Indexed;
}
if (fillBackgroundColor != null)
{
cellstyle.FillBackgroundColor = fillBackgroundColor.Indexed;
}
if (font != null)
{
cellstyle.SetFont(font);
}
//有边框
cellstyle.BorderBottom = BorderStyle.Thin;
cellstyle.BorderLeft = BorderStyle.Thin;
cellstyle.BorderRight = BorderStyle.Thin;
cellstyle.BorderTop = BorderStyle.Thin;
return cellstyle;
}
#endregion
#region
/// <summary>
/// 合并单元格
/// </summary>
/// <param name="sheet">要合并单元格所在的sheet</param>
/// <param name="rowstart">开始行的索引</param>
/// <param name="rowend">结束行的索引</param>
/// <param name="colstart">开始列的索引</param>
/// <param name="colend">结束列的索引</param>
public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
{
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
sheet.AddMergedRegion(cellRangeAddress);
}
#endregion
#region
public enum stylexls
{
,
url,
,
,
,
,
,
,
,
}
#endregion
#region
public static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
{
ICellStyle cellStyle = wb.CreateCellStyle();
//定义几种字体
//也可以一种字体,写一些公共属性,然后在下面需要时加特殊的
IFont font12 = wb.CreateFont();
font12.FontHeightInPoints = 10;
font12.FontName = "微软雅黑";
IFont font = wb.CreateFont();
font.FontName = "微软雅黑";
IFont fontcolorblue = wb.CreateFont();
fontcolorblue.Color = HSSFColor.OliveGreen.Blue.Index;
// fontcolorblue.IsItalic = true;//下划线
fontcolorblue.FontName = "微软雅黑";
/*
//边框
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Dotted;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Hair;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Hair;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Dotted;
//边框颜色
cellStyle.BottomBorderColor = HSSFColor.OliveGreen.Blue.Index;
cellStyle.TopBorderColor = HSSFColor.OliveGreen.Blue.Index;
//背景图形
cellStyle.FillForegroundColor = HSSFColor.White.Index;
// cellStyle.FillPattern = FillPatternType.NO_FILL;
cellStyle.FillBackgroundColor = HSSFColor.Blue.Index;
//水平对齐
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
//垂直对齐
cellStyle.VerticalAlignment = VerticalAlignment.Center;
//自动换行
cellStyle.WrapText = true;
//缩进;当设置为1时前面留的空白太大了。希旺官网改进。或者是我设置的不对
cellStyle.Indention = 0;
*/
//上面基本都是设共公的设置
//下面列出了常用的字段类型
switch (str)
{
case stylexls.:
// cellStyle.FillPattern = FillPatternType.LEAST_DOTS;
cellStyle.SetFont(font12);
break;
case stylexls.:
IDataFormat datastyle = wb.CreateDataFormat();
cellStyle.DataFormat = datastyle.GetFormat("yyyy/mm/dd");
cellStyle.SetFont(font);
break;
case stylexls.:
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
cellStyle.SetFont(font);
break;
case stylexls.:
IDataFormat format = wb.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("¥#,##0");
cellStyle.SetFont(font);
break;
case stylexls.url:
fontcolorblue.Underline = FontUnderlineType.Single;
cellStyle.SetFont(fontcolorblue);
break;
case stylexls.:
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");
cellStyle.SetFont(font);
break;
case stylexls.:
IDataFormat format1 = wb.CreateDataFormat();
cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0");
cellStyle.SetFont(font);
break;
case stylexls.:
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");
cellStyle.SetFont(font);
break;
case stylexls.:
cellStyle.SetFont(font);
break;
}
return cellStyle;
}
#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 + 1;
int system = 26;
char[] digArray = new char[100];
int i = 0;
while (index > 0)
{
int mod = index % system;
if (mod == 0) mod = system;
digArray[i++] = (char)(mod - 1 + 'A');
index = (index - 1) / 26;
}
StringBuilder sb = new StringBuilder(i);
for (int j = i - 1; j >= 0; j--)
{
sb.Append(digArray[j]);
}
return sb.ToString();
}
/// <summary>
/// 转化日期
/// </summary>
/// <param name="date">日期</param>
/// <returns></returns>
public static DateTime ConvertDate(string date)
{
DateTime dt = new DateTime();
string[] time = date.Split('-');
int year = Convert.ToInt32(time[2]);
int month = Convert.ToInt32(time[0]);
int day = Convert.ToInt32(time[1]);
string years = Convert.ToString(year);
string months = Convert.ToString(month);
string days = Convert.ToString(day);
if (months.Length == 4)
{
dt = Convert.ToDateTime(date);
}
else
{
string rq = "";
if (years.Length == 1)
{
years = "0" + years;
}
if (months.Length == 1)
{
months = "0" + months;
}
if (days.Length == 1)
{
days = "0" + days;
}
rq = "20" + years + "-" + months + "-" + days;
dt = Convert.ToDateTime(rq);
}
return dt;
}
/// <summary>
/// 给行创建简单的单元格(必须为以选中的字段)
/// </summary>
/// <param name="row">表格行</param>
/// <param name="index">列的位置</param>
/// <param name="value">值</param>
/// <param name="fild">当前字段</param>
/// <param name="checkedFilds">选中的字段列表</param>
public static void CreateSimpleCell(IRow row, ref int index, string value, string fild, string checkedFilds)
{
if (checkedFilds.IndexOf("[" + fild.ToUpper() + "]") > -1)
{
row.CreateCell(index).SetCellValue(value);
index++;
}
}
#endregion
}
public class ExcelCell
{
/// <summary>
/// 英文字段名称
/// </summary>
public string fild { get; set; }
/// <summary>
/// 字段的数据类型
/// </summary>
public string type { get; set; }
/// <summary>
/// 字段的中文标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 字段的值
/// </summary>
public string nvalue { get; set; }
}
}