Excel帮助类操作

public class ExcelHelper
{
/// <summary>
/// 将xls导入List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream"></param>
/// <param name="errorstr"></param>
/// <returns></returns>
public static List<T> ImportExcelXLS<T>(Stream stream, out string errorstr)
{
return ConvertDataTable<T>(ImportExcelXLS(stream, out errorstr));
}

public static List<T> ImportExcelXLSX<T>(Stream stream, out string errorstr)
{
return ConvertDataTable<T>(ExcelToTableForXLSX(stream, out errorstr));
}

/// <summary>
/// 读取xls文件
/// </summary>
/// <param name="stream"></param>
/// <param name="errorstr"></param>
/// <returns></returns>
public static DataTable ImportExcelXLS(Stream stream, out string errorstr)
{
try
{
errorstr = string.Empty;
HSSFWorkbook hssfworkbook;
using (Stream memstream = new MemoryStream())
{
using (stream)
{

byte[] bytes = new byte[1024];
int readBtyes;
while ((readBtyes = stream.Read(bytes, 0, bytes.Length)) > 0)
{
memstream.Write(bytes, 0, readBtyes);
}
}
memstream.Position = 0;
hssfworkbook = new HSSFWorkbook(memstream);
}
NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
NPOI.SS.UserModel.IRow rowHeader = sheet.GetRow(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

DataTable dt = new DataTable();
for (int i = 0; i < rowHeader.PhysicalNumberOfCells; i++)
{
dt.Columns.Add(Convert.ToChar(((int)'A') + i).ToString());
}
while (rows.MoveNext())
{
HSSFRow row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Columns.Count; i++)
{
NPOI.SS.UserModel.ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell)) //日期类型
{
dr[i] = cell.DateCellValue;
}
else //数值类型
{
dr[i] = cell.NumericCellValue;
}
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank) //空数据类型
{
dr[i] = "";
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula) //公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook);
dr[i] = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型处理
{
dr[i] = cell.StringCellValue;
}
}
dt.Rows.Add(dr);
}
return dt;

}
catch (Exception ex)
{
errorstr = ex.ToString();
return null;
}
}

/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(Stream stream, out string errorstr)
{

try
{
DataTable dt = new DataTable();
errorstr = string.Empty;
XSSFWorkbook xssfworkbook;
using (Stream memstream = new MemoryStream())
{

using (stream)
{

byte[] bytes = new byte[1024];
int readBtyes;
while ((readBtyes = stream.Read(bytes, 0, bytes.Length)) > 0)
{
memstream.Write(bytes, 0, readBtyes);
}
}
memstream.Position = 0;
xssfworkbook = new XSSFWorkbook(memstream);
}

NPOI.SS.UserModel.ISheet sheet = xssfworkbook.GetSheetAt(0);
NPOI.SS.UserModel.IRow rowHeader = sheet.GetRow(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
for (int i = 0; i < rowHeader.PhysicalNumberOfCells; i++)
{
dt.Columns.Add(Convert.ToChar(((int)'A') + i).ToString());
}
while (rows.MoveNext())
{
XSSFRow row = (XSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Columns.Count; i++)
{
NPOI.SS.UserModel.ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
if (cell == null)
{
dr[i] = null;
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell)) //日期类型
{
dr[i] = cell.DateCellValue;
}
else //数值类型
{
dr[i] = cell.NumericCellValue;
}
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank) //空数据类型
{
dr[i] = "";
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula) //公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(xssfworkbook);
dr[i] = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型处理
{
dr[i] = cell.StringCellValue;
}
}
dt.Rows.Add(dr);
}
return dt;
}
catch (Exception ex)
{
errorstr = ex.ToString();
return null;
}
}

/// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}

/// <summary>
/// 将DataTable转换List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
private static List<T> ConvertDataTable<T>(DataTable dt)
{

List<T> data = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
T item = GetItem<T>(dt.Rows[i]);
data.Add(item);
}
return data;
}

/// <summary>
/// 读取Data转换List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.GetCustomAttribute<ExcelAttribute>() != null && pro.GetCustomAttribute<ExcelAttribute>().ColumnName == dr.Table.Rows[0][column].ToString())
{
pro.SetValue(obj, Convert.ChangeType(dr[column.ColumnName], pro.PropertyType), null);
}
}
}
return obj;
}

public static MemoryStream ExportByList<T>(List<T> dtList, string strHeaderText, string loginName, out string errorstr, int sheetSize = 0xfde8)
{
return Export(ToDataTable<T>(dtList), strHeaderText, loginName, out errorstr, sheetSize);
}

private static DataTable ToDataTable<T>(List<T> list)
{
Type type = typeof(T);
using (DataTable table = new DataTable())
{
Type propertyType;
Type type3;
ExcelAttribute customAttribute;
string str;
DataRow row = table.NewRow();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo info in properties)
{
if (info.GetCustomAttribute<ExcelAttribute>() != null)
{
propertyType = info.PropertyType;
type3 = Nullable.GetUnderlyingType(propertyType) ?? propertyType;
customAttribute = info.GetCustomAttribute<ExcelAttribute>();
str = customAttribute.ColumnName + (string.IsNullOrEmpty(customAttribute.Format) ? "" : ("@$@" + customAttribute.Format));
table.Columns.Add(str, type3);
}
}
for (int i = 0; i < list.Count; i++)
{
DataRow row2 = table.NewRow();
foreach (PropertyInfo info in properties)
{
propertyType = info.PropertyType;
type3 = Nullable.GetUnderlyingType(propertyType) ?? propertyType;
customAttribute = info.GetCustomAttribute<ExcelAttribute>();
if (customAttribute != null)
{
str = customAttribute.ColumnName + (string.IsNullOrEmpty(customAttribute.Format) ? "" : ("@$@" + customAttribute.Format));
row2[str] = info.GetValue(list[i], null) ?? DBNull.Value;
}
}
table.Rows.Add(row2);
}
return table;
}
}

public static MemoryStream Export(DataTable dtSource, string strHeaderText, string loginName, out string errorstr, int sheetSize = 0xfde8)
{
MemoryStream stream2;
errorstr = "";
try
{
ISheet sheet;
string realColName;
int num2;
int num3;
HSSFWorkbook workbook = new HSSFWorkbook();
List<ISheet> list = new List<ISheet>();
for (int i = dtSource.Rows.Count; i > 0; i -= sheetSize)
{
sheet = workbook.CreateSheet();
list.Add(sheet);
}
if (list.Count == 0)
{
sheet = workbook.CreateSheet();
list.Add(sheet);
}
DocumentSummaryInformation information = PropertySetFactory.CreateDocumentSummaryInformation();
information.Company = "NPOI";
workbook.DocumentSummaryInformation = information;
SummaryInformation information2 = PropertySetFactory.CreateSummaryInformation();
information2.Author = "安鲜达";
information2.ApplicationName = "安鲜达";
information2.LastAuthor = loginName;
information2.Comments = loginName;
information2.Title = "安鲜达";
information2.Subject = "安鲜达表格";
information2.CreateDateTime = new DateTime?(DateTime.Now);
workbook.SummaryInformation = information2;
int[] numArray = new int[dtSource.Columns.Count];
foreach (DataColumn column in dtSource.Columns)
{
realColName = GetRealColName(column.ColumnName);
numArray[column.Ordinal] = Encoding.GetEncoding(0x3a8).GetBytes(realColName).Length;
}
for (num2 = 0; num2 < dtSource.Rows.Count; num2++)
{
num3 = 0;
while (num3 < dtSource.Columns.Count)
{
int length = Encoding.GetEncoding(0x3a8).GetBytes(dtSource.Rows[num2][num3].ToString()).Length;
if (length > numArray[num3])
{
numArray[num3] = length;
}
num3++;
}
}
ICellStyle style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
style.SetFont(font);
for (num2 = 0; num2 < list.Count; num2++)
{
IRow row = list[num2].CreateRow(0);
foreach (DataColumn column2 in dtSource.Columns)
{
realColName = GetRealColName(column2.ColumnName);
row.CreateCell(column2.Ordinal).SetCellValue(realColName);
row.GetCell(column2.Ordinal).CellStyle = style;
int num5 = numArray[column2.Ordinal] + 1;
if (num5 > 0xff)
{
num5 = 0xff;
}
list[num2].SetColumnWidth(column2.Ordinal, num5 * 0x100);
}
}
List<ICellStyle> list2 = new List<ICellStyle>();
for (num2 = 0; num2 < dtSource.Columns.Count; num2++)
{
string format = GetFormat(dtSource.Columns[num2].ColumnName);
if (string.IsNullOrEmpty(format))
{
list2.Add(null);
}
else
{
ICellStyle item = workbook.CreateCellStyle();
item.DataFormat = workbook.CreateDataFormat().GetFormat(format);
list2.Add(item);
}
}
int rownum = 1;
for (num2 = 0; num2 < list.Count; num2++)
{
rownum = 1;
int num7 = num2 * sheetSize;
int num8 = (((num2 + 1) * sheetSize) > dtSource.Rows.Count) ? dtSource.Rows.Count : ((num2 + 1) * sheetSize);
for (num3 = num7; num3 < num8; num3++)
{
DataRow row2 = dtSource.Rows[num3];
IRow row3 = list[num2].CreateRow(rownum);
for (int j = 0; j < dtSource.Columns.Count; j++)
{
DateTime minValue;
ICell cell = row3.CreateCell(dtSource.Columns[j].Ordinal);
string str3 = (row2[dtSource.Columns[j]] == null) ? string.Empty : row2[dtSource.Columns[j]].ToString().Trim();
switch (dtSource.Columns[j].DataType.ToString())
{
case "System.String":
{
cell.SetCellValue(str3);
continue;
}
case "System.DateTime":
{
minValue = DateTime.MinValue;
DateTime.TryParse(str3, out minValue);
if (list2[j] == null)
{
break;
}
cell.SetCellValue(minValue);
cell.CellStyle = list2[j];
continue;
}
case "System.Boolean":
{
bool result = false;
bool.TryParse(str3, out result);
cell.SetCellValue(result);
continue;
}
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
{
int num10 = 0;
int.TryParse(str3, out num10);
cell.SetCellValue((double)num10);
if (list2[j] != null)
{
cell.CellStyle = list2[j];
}
continue;
}
case "System.Decimal":
case "System.Double":
{
double num11 = 0.0;
double.TryParse(str3, out num11);
cell.SetCellValue(num11);
if (list2[j] != null)
{
cell.CellStyle = list2[j];
}
continue;
}
case "System.DBNull":
{
cell.SetCellValue("");
continue;
}
default:
goto Label_06B4;
}
cell.SetCellValue(minValue.ToString("yyyy/MM/dd HH:mm:ss"));
continue;
Label_06B4:
cell.SetCellValue("");
}
rownum++;
}
}
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
stream.Flush();
stream.Position = 0L;
stream2 = stream;
}
}
catch (Exception exception)
{
errorstr = JsonConvert.SerializeObject(exception);
stream2 = null;
}
return stream2;
}

private static string GetFormat(string oriName)
{
if (string.IsNullOrEmpty(oriName))
{
return null;
}
int index = oriName.IndexOf("@$@");
if (index == -1)
{
return null;
}
return oriName.Substring(index + "@$@".Length).Trim();
}

private static string GetRealColName(string oriName)
{
if (string.IsNullOrEmpty(oriName))
{
return oriName;
}
int index = oriName.IndexOf("@$@");
if (index == -1)
{
return oriName;
}
return oriName.Substring(0, index);
}

public static List<T> Import<T>(Stream stream, out string errorStr)
{
return ConvertDataTable<T>(Import(stream, out errorStr));
}
public static DataTable Import(Stream stream, out string errorStr)
{
try
{
errorStr = "";
HSSFWorkbook workbook = new HSSFWorkbook(stream);
ISheet sheetAt = workbook.GetSheetAt(0);
IRow row = sheetAt.GetRow(0);
IEnumerator rowEnumerator = sheetAt.GetRowEnumerator();
DataTable table = new DataTable();
for (int i = 0; i < row.PhysicalNumberOfCells; i++)
{
table.Columns.Add(Convert.ToChar((int)(0x41 + i)).ToString());
}
while (rowEnumerator.MoveNext())
{
HSSFRow current = (HSSFRow)rowEnumerator.Current;
DataRow row3 = table.NewRow();
for (int j = 0; j < table.Columns.Count; j++)
{
ICell cell = current.GetCell(j);
if (cell == null)
{
row3[j] = null;
}
else if (cell.CellType == CellType.Numeric)
{
if (DateUtil.IsCellDateFormatted(cell))
{
row3[j] = cell.DateCellValue;
}
else
{
row3[j] = cell.NumericCellValue;
}
}
else if (cell.CellType == CellType.Blank)
{
row3[j] = "";
}
else if (cell.CellType == CellType.Formula)
{
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
row3[j] = evaluator.Evaluate(cell).StringValue;
}
else
{
row3[j] = cell.StringCellValue;
}
}
table.Rows.Add(row3);
}
return table;
}
catch (Exception exception)
{
errorStr = JsonConvert.SerializeObject(exception);
return null;
}
}
}

Excel帮助类的更多相关文章

  1. excel工具类

    excel工具类 import com.iport.framework.util.ValidateUtil; import org.apache.commons.lang3.StringUtils; ...

  2. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  3. MVC NPOI Linq导出Excel通用类

    之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = , ...

  4. asp.net(C#) Excel导出类 导出.xls文件

    ---恢复内容开始--- using Microsoft.Office.Interop.Excel; 针对office 2003需添加引用Microsoft   Excel   11.0   Obje ...

  5. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  6. C#EXCEL 操作类--C#ExcelHelper操作类

    主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...

  7. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  8. 30 个 PHP 的 Excel 处理类

    下面的 PHP Excel 处理类中,包含 Excel 读写.导入导出等相关的类,列表如下: PHP Excel Reader classes 1. Read Excel Spreadsheets u ...

  9. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  10. 29 个 PHP 的 Excel 处理类

    下面的 PHP Excel 处理类中,包含 Excel 读写.导入导出等相关的类,列表如下: PHP Excel Reader classes 1. Read Excel Spreadsheets u ...

随机推荐

  1. Java实现 LeetCode 744 寻找比目标字母大的最小字母(二分法)

    744. 寻找比目标字母大的最小字母 给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母. 在比较时,数组里字母的是循环有序的.举个例 ...

  2. Java实现 LeetCode 526 优美的排列(DFS)

    526. 优美的排列 假设有从 1 到 N 的 N 个整数,如果从这 N 个数字中成功构造出一个数组,使得数组的第 i 位 (1 <= i <= N) 满足如下两个条件中的一个,我们就称这 ...

  3. Java实现 LeetCode 466 统计重复个数

    466. 统计重复个数 定义由 n 个连接的字符串 s 组成字符串 S,即 S = [s,n].例如,["abc", 3]="abcabcabc". 另一方面, ...

  4. java实现高斯日记

    题目标题: 高斯日记 大数学家高斯有个好习惯:无论如何都要记日记. 他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210 后来人们知道,那个整数就是日期,它表示那一天是高斯 ...

  5. java实现第七届蓝桥杯机器人塔

    机器人塔 X星球的机器人表演拉拉队有两种服装,A和B. 他们这次表演的是搭机器人塔. 类似: A B B A B A A A B B B B B A B A B A B B A 队内的组塔规则是: A ...

  6. 用vue实现一个简单的时间屏幕

    前言 去年用了一个小的 app,叫做 一个木函,本来想着用来做动画优化就删掉了的,不过看到他有个时间屏幕的小工具,就点进去看了下,觉得挺好玩的,就想着能不能自己实现一下. ps: 闲话不多说,先上例子 ...

  7. 搞清楚C语言指针

    Part 0:为什么要写这篇文章 C语言中的指针是C语言的精髓,也是C语言的重难点之一. 然而,很少有教程能把指针讲的初学者能听懂,还不会引起歧义. 本文章会尝试做到这一点,如有错误,请指出. Par ...

  8. CentOS 6.X 双网卡绑定配置

    相关环境 主机:Dell PowerEdge R720服务器(背板有4个GE网口) 操作系统:CentOS(RHEL)6.X 网线连接 使用6类网线 将Dell R720 GE网口 0,与交换机A相连 ...

  9. Azure AD(四)知识补充-服务主体

    一,引言 又到了新的一周了,也到了我新的分享的时间了,还记得上一周立得Flag,其中 “保证每周输出一篇文章” ,让我特别“在意”(这里用词不太恰当).主要是我的一个大学舍友,他突然问了我一个关于写博 ...

  10. (八)MySQL事务、视图、变量、存储过程、函数、流程控制结构

    补充:增删查改语句在数据库中基本通用,但这篇博客的内容基本是MySQL区别于其它数据库管理系统的知识,也要认真学习. 一.事务 1.含义:在MySQL中,可以通过创建事务来解决一些问题. 2.语法: ...