http://download.csdn.net/detail/diaodiaop/7611721

using System.Collections.Generic;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Text.RegularExpressions;
using System;
using System.Reflection;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema; public class MyExcelHelper
{
public class x2003
{
#region Excel2003
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLS(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xls)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLS(DataTable dt, string file)
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
hssfworkbook.Write(stream);
byte[] buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xls)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLS(HSSFCell 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;
}
}
#endregion
} public class x2007
{
#region Excel2007
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLSX(DataTable dt, string file)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
xssfworkbook.Write(stream);
byte[] buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <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;
}
}
#endregion
} public static DataTable GetDataTable(string filepath)
{
DataTable dt = new DataTable("xls");
if (Regex.IsMatch(filepath, ".xls$"))
{
dt = x2003.ExcelToTableForXLS(filepath);
}
else
{
dt = x2007.ExcelToTableForXLSX(filepath);
}
return dt;
} /// <summary>
/// 根据文件路径与单元头,获取我们需要的DataTable
/// </summary>
/// <param name="filepath">文件路径</param>
/// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } }</param>
/// <returns></returns>
public static DataTable GetDataTable(string filepath, Dictionary<string, string> cellHeard)
{
DataTable dt = new DataTable("xls");
if (Regex.IsMatch(filepath, ".xls$"))
{
dt = x2003.ExcelToTableForXLS(filepath);
}
else
{
dt = x2007.ExcelToTableForXLSX(filepath);
} DataTable result = createDataTableKey(cellHeard);
DataRow row;
foreach(DataRow r in dt.Rows)
{
row = result.NewRow();
foreach (KeyValuePair<string, string> kvp in cellHeard)
{
if (dt.Columns.Contains(kvp.Value))
{
row[kvp.Key] = r[kvp.Value];
}
else {
row[kvp.Key] = string.Empty;
}
}
result.ImportRow(row);
}
return dt;
} /// <summary>
/// 根据单元头的键转换成我们 需要的DataTable
/// </summary>
/// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } }</param>
/// <param name="dt">数据源</param>
/// <returns></returns>
public static DataTable ChangeDataTableKey(Dictionary<string, string> cellHeard,DataTable dt)
{
DataTable result = createDataTableKey(cellHeard);
DataRow row;
foreach (DataRow r in dt.Rows)
{
row = result.NewRow();
foreach (KeyValuePair<string, string> kvp in cellHeard)
{
if (dt.Columns.Contains(kvp.Value))
{
row[kvp.Key] = r[kvp.Value];
}
else
{
row[kvp.Key] = string.Empty;
}
}
result.Rows.Add(row);
}
return result;
} /// <summary>
/// 根据单元头值转换成我们 需要的DataTable
/// </summary>
/// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } }</param>
/// <param name="dt">数据源</param>
/// <returns></returns>
public static DataTable ChangeDataTableValue(Dictionary<string, string> cellHeard, DataTable dt)
{
DataTable result = createDataTableValue(cellHeard);
DataRow row;
foreach (DataRow r in dt.Rows)
{
row = result.NewRow();
foreach (KeyValuePair<string, string> kvp in cellHeard)
{
if (dt.Columns.Contains(kvp.Value))
{
row[kvp.Value] = r[kvp.Value];
}
else
{
row[kvp.Value] = string.Empty;
}
}
result.Rows.Add(row);
}
return result;
} private static DataTable createDataTableValue(Dictionary<string, string> cellHeard)
{
DataTable dt = new DataTable();
foreach (KeyValuePair<string, string> kvp in cellHeard)
{
DataColumn col = new DataColumn(kvp.Value);
dt.Columns.Add(col);
}
return dt;
} private static DataTable createDataTableKey(Dictionary<string, string> cellHeard)
{
DataTable dt = new DataTable();
foreach (KeyValuePair<string, string> kvp in cellHeard)
{
DataColumn col = new DataColumn(kvp.Key);
dt.Columns.Add(col);
}
return dt;
} public static List<T> ConvertToList<T>(DataTable dt) where T : new()
{
// 定义集合
List<T> list = new List<T>(); // 获得此模型的类型
Type type = typeof(T);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行 // 获得此模型的公共属性
PropertyInfo[] propertys = (new T()).GetType().GetProperties();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
list.Add(t);
} return list; }
} [Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
public SerializableDictionary() { }
public void WriteXml(XmlWriter write) // Serializer
{
XmlSerializer KeySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer ValueSerializer = new XmlSerializer(typeof(TValue)); foreach (KeyValuePair<TKey, TValue> kv in this)
{
write.WriteStartElement("SerializableDictionary");
write.WriteStartElement("key");
KeySerializer.Serialize(write, kv.Key);
write.WriteEndElement();
write.WriteStartElement("value");
ValueSerializer.Serialize(write, kv.Value);
write.WriteEndElement();
write.WriteEndElement();
}
}
public void ReadXml(XmlReader reader) // Deserializer
{
reader.Read();
XmlSerializer KeySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer ValueSerializer = new XmlSerializer(typeof(TValue)); while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("SerializableDictionary");
reader.ReadStartElement("key");
TKey tk = (TKey)KeySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue vl = (TValue)ValueSerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadEndElement();
this.Add(tk, vl);
reader.MoveToContent();
}
reader.ReadEndElement(); }
public XmlSchema GetSchema()
{
return null;
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//DataTable enlist2 = MyExcelHelper.ChangeDataTableValue(GetHead(), MyExcelHelper.GetDataTable(@"E:\代码&数据备份\宁海专项资金\01代码\NhFunds\SFWebSite\UpFiles\ExcelFiles\地方贡献审核明细表模板.xls")); //datagrid1.DataSource = enlist2;
//datagrid1.DataBind();
//Session[_key] = enlist2; //return;
StringBuilder errorMsg = new StringBuilder(); // 错误信息
try
{ #region 1.获取Excel文件并转换为一个List集合 // 1.1存放Excel文件到本地服务器
HttpPostedFile filePost = Request.Files["filed"]; // 获取上传的文件
if (filePost == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('请选择文件上传');", true);
return;
}
string filePath = SaveExcelFile(filePost); // 保存文件并获取文件路径
if (string.IsNullOrEmpty(filePath))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('文件上传失败');", true);
return;
} // 单元格抬头
// key:实体对象属性名称,可通过反射获取值
// value:属性对应的中文注解
Dictionary<string, string> cellheader = GetHead(); DataTable enlist = MyExcelHelper.ChangeDataTableValue(cellheader, MyExcelHelper.GetDataTable(filePath));
List<lz.T_GongXian> list = MyExcelHelper.ConvertToList<lz.T_GongXian>(MyExcelHelper.ChangeDataTableValue(cellheader, enlist));
datagrid1.DataSource = enlist;
datagrid1.DataBind();
Session[_key] = enlist;
#endregion // 3.TODO:对List集合进行持久化存储操作。如:存储到数据库 // 4.返回操作结果 }
catch (Exception ex)
{
throw ex;
}
} private Dictionary<string, string> GetHead()
{ SerializableDictionary<string, string> cellheader = new SerializableDictionary<string, string>();
cellheader.Add("id", "序号");
cellheader.Add("QYMC", "企业名称");
cellheader.Add("SBXM", "申报项目");
cellheader.Add("SDBZJY", "审定补助金额");
cellheader.Add("ZZS", "增值税(含免抵)");
cellheader.Add("YYS", "营业税");
cellheader.Add("GRSDS", "个人所得税(仅限个人独资企业)");
cellheader.Add("QYSDS", "企业所得税");
cellheader.Add("YHS", "印花税");
cellheader.Add("CJS", "城建税");
cellheader.Add("FCS", "房产税");
cellheader.Add("TDSYS", "土地使用税");
cellheader.Add("DFLCHJ", "地方留成合计数");
cellheader.Add("BZCY", "地方留成合计数与审定补助合计数差额");
cellheader.Add("HDBZZJ", "核定补助资金");
cellheader.Add("remark", "备注"); return cellheader;
 }

Nopi Excel导入的更多相关文章

  1. nopi excel 导入

    #region 从Excel导入 /// <summary> /// 读取excel ,默认第一行为标头 /// </summary> /// <param name=& ...

  2. C# Excel导入、导出【源码下载】

    本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...

  3. C# Excel导入、导出

    本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...

  4. 企业级自定义表单引擎解决方案(十六)--Excel导入导出

    Excel对于后端管理系统来说,永远都是绕不开的话题,开发Excel导入导出功能往往都比较麻烦,因为涉及到Excel导入模板制作.Excel表格数据与系统数据库表字段映射.Excel导入数据验证.验证 ...

  5. ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出-自定义表模导入

    系列目录 前言 上一节使用了LinqToExcel和CloseXML对Excel表进行导入和导出的简单操作,大家可以跳转到上一节查看: ASP.NET MVC5+EF6+EasyUI 后台管理系统(6 ...

  6. 解析大型.NET ERP系统 设计通用Microsoft Excel导入功能

    做企业管理软件很难避免与Microsoft Excel打交道,常常是软件做好了,客户要求说再做一个Excel导入功能.导入Excel数据的功能的难度不大,从Excel列数据栏位的取值,验证值,再导入到 ...

  7. (转)高效的将excel导入sqlserver中

    大部分人都知道用oledb来读取数据到dataset,但是读取之后怎么处理dataset就千奇百怪了.很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,System.Data.SqlClie ...

  8. 安全的将excel导入sqlite3的解决方案

    最近在做一个小项目时,需要把一个excel中的数据保存到sqlite3数据库中以备后用,表中有字符也有数字,要用到特定的数据类型方便后续使用,参照网上的方法,将excel文件转换为csv文件后,在导入 ...

  9. 利用反射实现通用的excel导入导出

    如果一个项目中存在多种信息的导入导出,为了简化代码,就需要用反射实现通用的excel导入导出 实例代码如下: 1.创建一个 Book类,并编写set和get方法 package com.bean; p ...

随机推荐

  1. Matlab下多径衰落信道的仿真

    衰落信道参数包括多径扩展和多普勒扩展.时不变的多径扩展相当于一个延时抽头滤波器,而多普勒扩展要注意多普勒功率谱密度,通常使用Jakes功率谱.高斯.均匀功率谱. 多径衰落信道由单径信道叠加而成,而单径 ...

  2. Cross platform GUI for creating SSL certs with OpenSSL

    Someone said: from : https://micksmix.wordpress.com/2012/08/09/xca-cross-platform-gui-for-creating-s ...

  3. LuaBridge 中C++类和继承示例

    luabridge不是一个陌生的名字,GIT上已经有3-4年多没有更新.将lua和C++相互调用封装的很方便,比如以下示例代码: /////////////////////////////////// ...

  4. vsftp FTP服务器 server settings , and add different users

    建议阅读知识:http://linux.vbird.org/linux_basic/0210filepermission.php  这是关于档案权限,用户,组等的问题.介绍的很有意思. 1. Inst ...

  5. Asp.net Mvc4默认权限详细(上)

    Asp.net Mvc4默认权限详细(上) 前言 上篇的菜鸟去重复之Sql的问题还没有得到满意的答案.如果哪位大哥有相关的资料解释,能够分享给我,那就太谢谢了. 以后每发表一篇博文我都会将以前遗留的问 ...

  6. hdu 2444

    这道题要先判断图是不是二分图,如果不是的话,就直接输出No,是的话就求最大匹配, 建边是双向的所以要/2 判断二分图:对点进行染色,如果A与B认识,A,B的颜色要不同, 如果出现颜色相同的就矛盾了,就 ...

  7. oracle-计算工作日

    数据库模拟表如下 operate_id operate_type operate_date process_sn 1 GD 2013-09-15 17:18:37 10001 2 JD 2013-09 ...

  8. 二、mongo数据库

    官网:https://www.mongodb.com/ 进入官网 右上角有个下载按钮Download 1.完成安装后:运行--cmd(命令面板) 2.常用命令: 打开数据库 mongod –dbpat ...

  9. IOS开发自定义tableviewcell的注意点😄

    自定义tableviewcell 1.xib,nib拖控件:awakefromnib: 设置2,不拖控件:- (instancetype)initWithStyle:(UITableViewCellS ...

  10. flume 以 kafka 为channel 的配置

    #此配置以kafka的一个topic为channel,相比其他channel类型 file和cache 兼并了快和安全的要求!# Define a kafka channel a1.channels. ...