ExcelHelper

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ExcelHelper相关的知识,希望对你有一定的参考价值。

using MedicalSystem.Bev.Domain.Attributes;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Sky.APP.Common
{
public class ExcelHelper
{
#region DataTable导出到Excel文件 Export(dtSource,strHeaderText,strFileName)

public static void Export<T>(List<T> dtSource, string strHeaderText, string strFileName)
{
DataTable dt = ToDataTable<T>(dtSource);
Export(dt, strHeaderText, strFileName);
}

public static void Export<T>(ObservableCollection<T> dtSource, string strHeaderText, string strFileName)
{
DataTable dt = ToDataTable<T>(dtSource);
Export(dt, strHeaderText, strFileName);
}

/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(IEnumerable<T> list)
{
//获得反射的入口
Type type = typeof(T);
Dictionary<PropertyInfo, ReportTitleAttribute> pList = new Dictionary<PropertyInfo, ReportTitleAttribute>();
//获取需要显示的属性(ReportTitleAttribute)
foreach (var pi in type.GetProperties())
{
ReportTitleAttribute atu = pi.GetCustomAttribute(typeof(ReportTitleAttribute), false) as ReportTitleAttribute;
if (atu != null && atu.ShowColumn)
{
pList.Add(pi, atu);
}
}
pList = pList.OrderBy(r => r.Value.ShowIndex).ToDictionary(r => r.Key, r => r.Value);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
//有些属性是可为空的,特殊处理
foreach (KeyValuePair<PropertyInfo, ReportTitleAttribute> kv in pList)
{
Type colType = kv.Key.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dt.Columns.Add(new DataColumn(kv.Value.Title, colType));
}
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
foreach (KeyValuePair<PropertyInfo, ReportTitleAttribute> kv in pList)
{
row[kv.Value.Title] = kv.Key.GetValue(item, null);
}
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}

/// <summary>
/// DataTable导出到Excel文件 Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="strHeaderText">Excel表头文本(例如:车辆列表)</param>
/// <param name="strFileName">保存位置</param>
public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
{
using (MemoryStream ms = Export(dtSource, strHeaderText))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
StreamReader reader = null;
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
}
#endregion

#region DataTable导出到Excel的MemoryStream Export(dtSource,strHeaderText)
/// <summary>
/// DataTable导出到Excel的MemoryStream Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="strHeaderText">Excel表头文本(例如:车辆列表)</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 = System.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;
int rowIndex = 1;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 1)
{
if (rowIndex != 1)
{
sheet = workbook.CreateSheet();
}

#region 表头及样式
{
//IRow headerRow = sheet.CreateRow(0);
IRow headerRow = sheet.CreateRow(1);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(1).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(1).CellStyle = headStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 1, dtSource.Columns.Count)); //合并表头
//sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
}
#endregion

#region 列头及样式
{
// IRow headerRow = sheet.CreateRow(1);
IRow headerRow = sheet.CreateRow(2);
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.CENTER; // ------------------
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 12;
font.FontName = "微软雅黑";
font.Boldweight = 500;
headStyle.SetFont(font);
headStyle.BorderTop = CellBorderType.THIN;
headStyle.BorderLeft = CellBorderType.THIN;
headStyle.BorderBottom = CellBorderType.THIN;
headStyle.BorderRight = CellBorderType.THIN;
headStyle.FillBackgroundColor = HSSFColor.MAROON.index;
headStyle.FillForegroundColor = HSSFColor.WHITE.index;
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal + 1).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal + 1).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(column.Ordinal + 1, (arrColWidth[column.Ordinal] + 2) * 300);
}
}
#endregion

//rowIndex = 2;
rowIndex = 3;
}
#endregion

#region 填充内容
IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.Height = 400;
ICellStyle rowStyle = workbook.CreateCellStyle();
rowStyle.Alignment = HorizontalAlignment.CENTER;
rowStyle.BorderTop = CellBorderType.DOTTED;
rowStyle.BorderLeft = CellBorderType.THIN;
rowStyle.BorderBottom = CellBorderType.DOTTED;
rowStyle.BorderRight = CellBorderType.THIN;
IFont font2 = workbook.CreateFont();
font2.FontHeightInPoints = 10;
font2.Boldweight = 300;
font2.FontName = "微软雅黑";
rowStyle.SetFont(font2);
if (rowIndex == dtSource.Rows.Count + 2)
{
rowStyle.BorderBottom = CellBorderType.THIN;
}
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal + 1);
string drValue = row[column].ToString();
switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.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;
}
dataRow.GetCell(column.Ordinal + 1).CellStyle = rowStyle;
}
#endregion

rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet.Dispose();
return ms;
}
}
#endregion

#region 读取excel,导入到DataTable,默认第二行为标头Import()
/// <summary>
/// 读取excel ,默认第二行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheet("UserInfo"); //因为可能包含隐藏模板,使用sheet名字来获取sheet
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(2);
if (headerRow == null)
{
return null;
}
// int fisrtCellCount = headerRow.FirstCellNum;
// int lastCellCount = headerRow.LastCellNum;
int fisrtCellCount = 1;//写死,防止实施乱修改模板
int lastCellCount = 18;//写死,防止实施乱修改模板
for (int j = fisrtCellCount; j < lastCellCount; j++)
{
ICell cell = headerRow.GetCell(j);
object obj = GetValueTypeForXLS(cell as HSSFCell);
if (obj == null || obj.ToString() == string.Empty || string.IsNullOrEmpty(obj.ToString().Trim()))
{
dt.Columns.Add("空白" + (j - fisrtCellCount).ToString());
continue;
}
string name = obj.ToString().Trim();
if (dt.Columns.Contains(name))
{
dt.Columns.Add("标题重复" + (j - fisrtCellCount).ToString());
}
else
{
dt.Columns.Add(name);
}
}

// int firstRowNum = sheet.FirstRowNum;
int firstRowNum = 0; //写死,防止实施乱修改模板
for (int i = (firstRowNum + 3); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);


if (row == null || string.IsNullOrWhiteSpace(row.Cells[1].StringCellValue)) //第二个cell保存的是工号,如果工号为空,此行直接跳过
{
continue;
}
DataRow dataRow = dt.NewRow();
for (int j = fisrtCellCount; j < lastCellCount; j++)
{
object obj = GetValueTypeForXLS(row.GetCell(j) as HSSFCell);
if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
{
dataRow[j - fisrtCellCount] = "";
continue;
}
dataRow[j - fisrtCellCount] = obj.ToString().Trim();
}
dt.Rows.Add(dataRow);
}
return dt;
}

private static object GetValueTypeForXLS(HSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.BLANK:
return null;
case CellType.BOOLEAN:
return cell.BooleanCellValue;
case CellType.NUMERIC:
if(DateUtil.IsCellDateFormatted(cell))
{
return cell.DateCellValue;
}
return cell.NumericCellValue;
case CellType.STRING:
return cell.StringCellValue;
case CellType.ERROR: //ERROR:
return cell.ErrorCellValue;
case CellType.FORMULA: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion
}
}

以上是关于ExcelHelper的主要内容,如果未能解决你的问题,请参考以下文章