NPOI 1.1
1 .NPOI 版本2.1
2. NPOI 读取execl
3.导入数据(SqlBulkCopy)
示例代码:
public class ImportServerData
{ DataTable dt_ItemInfo = new DataTable(); public StringBuilder WaringMsg { get; set; } public string ParentDeptCode { get; set; }
/// <summary>
/// 初始化结构
/// </summary>
public ImportServerData()
{
#region dt_ItemInfo
dt_ItemInfo.Columns.Add("ID", typeof(string));
dt_ItemInfo.Columns.Add("NeedUnit", typeof(string));
dt_ItemInfo.Columns.Add("ItemType", typeof(string));
dt_ItemInfo.Columns.Add("Name", typeof(string));
dt_ItemInfo.Columns.Add("ItemInfo", typeof(string));
dt_ItemInfo.Columns.Add("Leader", typeof(string));
dt_ItemInfo.Columns.Add("SugDoUnit", typeof(string));
dt_ItemInfo.Columns.Add("State", typeof(int));
dt_ItemInfo.Columns.Add("LinkMan", typeof(string));
dt_ItemInfo.Columns.Add("IsDel", typeof(string));
dt_ItemInfo.Columns.Add("IsShow", typeof(string));
dt_ItemInfo.Columns.Add("AddTime", typeof(DateTime));
dt_ItemInfo.Columns.Add("SourceType", typeof(string));
dt_ItemInfo.Columns.Add("ParentDeptCode", typeof(string));
dt_ItemInfo.Columns.Add("OperateSpeed", typeof(string));
dt_ItemInfo.Columns.Add("Approval", typeof(string));
dt_ItemInfo.Columns.Add("Year", typeof(int));
dt_ItemInfo.Columns.Add("LinkTel", typeof(string));
dt_ItemInfo.Columns.Add("SugDoUnitMan", typeof(string));
dt_ItemInfo.Columns.Add("SugDoUnitTel", typeof(string));
dt_ItemInfo.Columns.Add("NodeState", typeof(string));
dt_ItemInfo.Columns.Add("Remark", typeof(string));
dt_ItemInfo.Columns.Add("SugDoUnitName", typeof(string));
dt_ItemInfo.Columns.Add("Source", typeof(string));
dt_ItemInfo.AcceptChanges();
#endregion
} /// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <returns>返回的DataTable</returns>
public bool ExcelToDataTable(string fileName)
{
ISheet sheet = null;
FileStream fs;
//事件类型 来源
string sql = "select Id,Name From dbo.Per_Dictionary where type in ('36','37')";
DataTable dtDictionary = Ruihua.Common.DapperHelper.Query(sql).Tables[]; //需求部门
string sqlbaseinfo = "select Id,unitName Name from dbo.DS_DW_BaseIfo ";
DataTable dtBaseInfo = Ruihua.Common.DapperHelper.Query(sqlbaseinfo).Tables[]; //承办单位
string sqlSugDoUnit = "select ArchitectureId Id, Caption Name From dbo.Architecture";
DataTable dtSugDoUnit = Ruihua.Common.DapperHelper.Query(sqlSugDoUnit).Tables[]; //领导
string sqlleader = "select Id,username Name From usr_user ";
DataTable dtLeader = Ruihua.Common.DapperHelper.Query(sqlleader).Tables[]; bool flag = false;
string currindex = "";
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
HSSFWorkbook workbook = new HSSFWorkbook(fs); for (int i = ; i < ; i++)
{
sheet = workbook.GetSheetAt(i); System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
string scouretext = (i == ? "市外联办研提事项" : i == ? "区领导走访征询事项" : "中央单位来函事项");
var scoureDr = dtDictionary.AsEnumerable().Where(w => w.Field<string>("Name") == scouretext).FirstOrDefault();
string scoureId = scoureDr != null ? scoureDr["Id"].ToString() : "";
int year = ;
int index = ;
while (rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
currindex = GetValue<string>(row, , );
if (currindex == "") continue;
if (index == )
{
string name = GetValue<string>(row, index, );
if (name != "") year = Convert.ToInt32(name.Substring(, ));
}
string waringinfo = "";
if (index >= )
{ string guid = Guid.NewGuid().ToString(); #region 需求单位 1 string unitname = Regex.Replace(GetValue<string>(row, , ), @"\s", ""); string needunitId = "";
bool isneedunit = false;
for (int n = ; n < dtBaseInfo.Rows.Count; n++)
{
bool falg = false;
for (int j = ; j < unitname.Length; j++)
{
string result = IsMatch(dtBaseInfo.Rows[n]["Name"].ToString(), unitname[j].ToString());
if (result == "")
{
break;
}
else
{
falg = true;
}
if (unitname.Length - == j && falg)
{
//这里只需要一条数据 就跳出循环
isneedunit = true;
needunitId = dtBaseInfo.Rows[n]["Id"].ToString();
break; }
if (isneedunit) break;
} } if (needunitId == "")
{
waringinfo += "[需求单位匹配失败]";
}
#endregion #region 事项类型
//事项类型(有多个类型) 3 、 string itemtypename = GetValue<string>(row, , ).Replace("\n", "").Replace("\r\n", "");
string[] itemNames = itemtypename != "" ? Regex.Replace( itemtypename, @"\s", "" ).Split('、') : null;
string itemTypeId = "";
if (itemNames != null)
{
var itemTypeDr = dtDictionary.AsEnumerable().Where(w => itemNames.Contains(w.Field<string>("Name"))); if (itemTypeDr == null || itemTypeDr.Count() == )
{
waringinfo += "[事项类型匹配失败多个类型用、分割]";
}
else
{
foreach (var item in itemTypeDr)
{
itemTypeId += item != null ? item["Id"].ToString() + "," : "";
}
itemTypeId = itemTypeId.Substring(, itemTypeId.Length - );
}
}
else
{
waringinfo += "[事项类型匹配失败多个类型用、分割]";
}
#endregion //承办单位 7
var itemSugDoUnit = dtSugDoUnit.AsEnumerable().Where(w => w.Field<string>("Name") == GetValue<string>(row, , )).FirstOrDefault();
string sugDoUnitId = "";
if (itemSugDoUnit != null)
{
sugDoUnitId = itemSugDoUnit["Id"].ToString();
}
//else{
// waringinfo += "[承办单位匹配失败]";
//}
string SugDoUnitName = GetValue<string>(row, , );
if (SugDoUnitName == "" && sugDoUnitId == "")
{
waringinfo += "[承办单位不能为空]";
}
//主管区领导 6
var itemLeader = dtLeader.AsEnumerable().Where(w => w.Field<string>("Name") == GetValue<string>(row, , )).FirstOrDefault();
string leaderId = "";
if (itemLeader != null)
{
leaderId = itemLeader["Id"].ToString();
}
else
{
waringinfo += "[主管区领导匹配失败]";
}
string ItemName = GetValue<string>(row, , );
if (ItemName == "ERROROVERTOP")
{
waringinfo += "[事项名称字符超出]";
}
string ItemInfo = GetValue<string>(row, , );
if (ItemInfo == "ERROROVERTOP")
{
waringinfo += "[需求事项字符超出]";
}
int State = GetStateByName(GetValue<string>(row, , ).Trim());
if (State == -)
{
waringinfo += "[办理状态匹配失败]";
}
string LinkMan = GetValue<string>(row, , );
if (LinkMan == "ERROROVERTOP")
{
waringinfo += "[中央单位联系人字符超出]";
}
string OperateSpeed = GetValue<string>(row, , );
if (OperateSpeed == "ERROROVERTOP")
{
waringinfo += "[办理结果(进展情况)字符超出]";
}
//string cc = MergedRegionValue(sheet, index,5);
string Approval = MergedRegionValue(sheet, index, );
if (Approval == "ERROROVERTOP")
{
waringinfo += "[领导批示字符超出]";
}
string LinkTel = GetValue<string>(row, , );
if (LinkTel == "ERROROVERTOP")
{
waringinfo += "[联系电话字符超出]";
}
string SugDoUnitMan = GetValue<string>(row, , );
if (SugDoUnitMan == "ERROROVERTOP")
{
waringinfo += "[承办单位联系人字符超出]";
}
string SugDoUnitTel = GetValue<string>(row, , );
if (SugDoUnitTel == "ERROROVERTOP")
{
waringinfo += "[联系电话字符超出]";
}
string Remark = GetValue<string>(row, , );
if (Remark == "ERROROVERTOP")
{
waringinfo += "[备注字符超出]";
}
if (waringinfo != "")
{
string sheetname = (i == ? "研提事项" : i == ? "走访(来访)事项" : "来函事项");
if (WaringMsg == null)
{
WaringMsg = new StringBuilder();
}
WaringMsg.Append(sheetname + "提示信息:序号[" + currindex + "]" + waringinfo + "\r\n");
} if (waringinfo == "")
{
//处理ItemInfo
dt_ItemInfo.Rows.Add(guid,
needunitId,
itemTypeId,
ItemName,
ItemInfo,
leaderId,
sugDoUnitId,
State,
LinkMan,
, ,
DateTime.Now,
, ParentDeptCode,
OperateSpeed,
Approval, year,
LinkTel,
SugDoUnitMan,
SugDoUnitTel,
GetNodeStateByName(GetValue<string>(row, , )),
Remark,
SugDoUnitName,
scoureId
);
} }
index++;
} }
dt_ItemInfo.AcceptChanges();
flag = true;
}
catch (Exception ex)
{
flag = false;
Ruihua.Log4Net.LogHelper.SaveLogError(new Log4Net.LogMessage { Info = "Exception: " + currindex + "序号" + ex.Message.ToString(), UserID = "" });
}
return flag;
}
private string MergedRegionValue(ISheet sheet, int rowNum, int colNum)
{
for (int i = ; i < sheet.NumMergedRegions; i++)
{
CellRangeAddress range = sheet.GetMergedRegion(i);
sheet.IsMergedRegion(range);
if (range != null)
{
if (range.FirstRow <= rowNum && range.LastRow >= rowNum && range.FirstColumn <= colNum && range.LastColumn >= colNum)
{ return sheet.GetRow(range.FirstRow).GetCell(range.FirstColumn).StringCellValue.ToString();
}
}
}
return "";
} private string GetValue<T>(IRow row, int index, int strlength)
{ string result = ""; if (typeof(string) == typeof(T))
{
ICell cell = row.GetCell(index);
if (cell != null)
{
if (cell.IsMergedCell)
{
result = cell.StringCellValue.ToString();
}
else if (strlength == )
{
result = cell.ToString();
}
else if (strlength > && cell.ToString().Length < strlength)
{
result = cell.ToString();
}
else
{
result = "ERROROVERTOP";
}
}
}
else if (typeof(int) == typeof(T))
{
ICell cell = row.GetCell(index); if (cell != null)
{
if (IsInteger(cell.ToString()))
{
result = cell.ToString(); }
}
}
else if (typeof(DateTime) == typeof(T))
{
ICell cell = row.GetCell(index); if (cell != null)
{
if (IsDatetTime(cell.ToString()))
{
result = cell.ToString(); }
}
}
return result;
} private int GetStateByName(string name)
{
int result = -;
switch (name)
{
case "未办结":
case "以主动对接,建立工作关系":
case "召开专项协调会":
case "组织现场踏勘":
case "正在处理":
case "正在商有关单位":
result = ;
break;
case "已办结":
case "已办结并反馈":
result = ;
break;
case "现行政策不能办理":
result = ;
break;
}
return result;
} private string GetNodeStateByName(string name)
{
string NodeState = ""; string[] nodename = name.Split(',');
for (int i = ; i < nodename.Length; i++)
{
switch (nodename[i].Trim())
{
case "以主动对接,建立工作关系":
NodeState += "0,";
break;
case "召开专项协调会":
NodeState += "1,";
break;
case "组织现场踏勘":
NodeState += "2,";
break;
case "正在处理":
NodeState += "3,";
break;
case "正在商有关单位":
NodeState += "4,";
break;
case "已办结":
NodeState += "5,";
break;
case "已办结并反馈":
NodeState += "6,";
break; }
}
return NodeState.Length > ? NodeState.Substring(, NodeState.Length - ) : NodeState;
} ///
/// </summary>
/// <param name="connectionString">目标连接字符</param>
/// <param name="TableName">目标表</param>
/// <param name="dt">源数据</param>
private void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
sqlbulkcopy.DestinationTableName = TableName;
sqlbulkcopy.BulkCopyTimeout = ;
sqlbulkcopy.BatchSize = ;
for (int i = ; i < dt.Columns.Count; i++)
{
sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
}
sqlbulkcopy.WriteToServer(dt);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
} /// <summary>
/// 验证整数
/// </summary>
/// <param name="input">待验证的字符串</param>
/// <returns>是否匹配</returns>
public static bool IsInteger(string input)
{ bool foundMatch = false;
try
{
foundMatch = Regex.IsMatch(input, @"-?\d+$");
}
catch (ArgumentException ex)
{
// Syntax error in the regular expression
}
return foundMatch;
} /// <summary>
/// 验证日期 yyyy-MM-dd
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsDatetTime(string input)
{ bool foundMatch = false;
try
{
foundMatch = Regex.IsMatch(input, "(19|20)[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])");
}
catch (ArgumentException ex)
{
// Syntax error in the regular expression
}
return foundMatch;
} public string ImportData(string fileName)
{
try
{
ExcelToDataTable(fileName);
int count = dt_ItemInfo.Rows.Count;
if (count > )
{
SqlBulkCopyByDatatable(DapperHelper.connectionString, "DS_FW_ItemInfo", dt_ItemInfo); return "成功导入:" + count.ToString() + "条数据!\r\n" + (WaringMsg != null ? WaringMsg.ToString() : ""); }
else
{
return WaringMsg != null ? WaringMsg.ToString() : "NO";
}
}
catch (Exception)
{
}
return WaringMsg != null ? WaringMsg.ToString() : "NO";
} public string IsMatch(string inputstr, string regexstr)
{ if (Regex.IsMatch(inputstr, regexstr))
{
return inputstr;
}
return "";
}
}
NPOI 1.1的更多相关文章
- .NET Core 首例 Office 开源跨平台组件(NPOI Core)
前言 最近项目中,需要使用到 Excel 导出,找了一圈发现没有适用于 .NET Core的,不依赖Office和操作系统限制的 Office 组件,于是萌生了把 NPOI 适配并移植到 .NET C ...
- 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)
很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...
- C#通过NPOI操作Excel
参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...
- 基于NPOI的Excel数据导入
从Excel导入数据最令人头疼的是数据格式的兼容性,特别是日期类型的兼容性.为了能够无脑导入日期,折腾了一天的NPOI.在经过测试确实可以导入任意格式的合法日期后,写下这篇小文,与大家共享.完整代码请 ...
- NPOI导出Excel
using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...
- 通过NPOI操作Excel
最近在做的一个项目中需要生成Excel,通过学习使用NPOI实现了相关需求,写了一个简便操作的类,记录如下: public class NPOIHelperForExcel { #region exc ...
- .Net开源Excel、Word操作组件-NPOI、EPPlus、DocX
一.NPOI 简介: NPOI is the .NET version of POI Java project. With NPOI, you can read/write Office 2003/2 ...
- 转载 NPOI Excel 单元格背景颜色对照表
NPOI Excel 单元格颜色对照表,在引用了 NPOI.dll 后可通过 ICellStyle 接口的 FillForegroundColor 属性实现 Excel 单元格的背景色设置,FillP ...
- 转载 NPOI.dll 用法。单元格,样式,字体,颜色,行高,宽度。读写excel
我用的版本是1.25的.每个版本用法有一点不同 using System; using System.Collections.Generic; using System.ComponentModel; ...
- NPOI操作EXCEL(六)——矩阵类表头EXCEL模板的解析
哈哈~~~很高兴还活着.总算加班加点的把最后一类EXCEL模板的解析做完了... 前面几篇文章介绍了博主最近项目中对于复杂excel表头的解析,写得不好,感谢园友们的支持~~~ 今天再简单讲诉一下另一 ...
随机推荐
- 《代码整洁之道》ch5~ch9读书笔记 PB16110698(~3.15) 第二周
<代码整洁之道>ch5~ch9读书笔记 本周我阅读了本书的第5~9章节,进一步了解整洁代码需要注意的几个方面:格式.对象与数据结构.错误处理.边界测试.单元测试和类的规范.以下我将分别记录 ...
- 基于Java Properties类设置本地配置文件
一.Java Properties类介绍 Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件, ...
- JS流程控制语句 做判断(if语句)if语句是基于条件成立才执行相应代码时使用的语句。语法:if(条件) { 条件成立时执行代码}
做判断(if语句) if语句是基于条件成立才执行相应代码时使用的语句. 语法: if(条件) { 条件成立时执行代码} 注意:if小写,大写字母(IF)会出错! 假设你应聘web前端技术开发岗位,如果 ...
- shell 版本号比较_用shell如何比较软件版本号的大小
比如你想写个脚本来比较两个版本号 (如"1.2.30" 和"1.3.0")来辨认哪个版本是最新的,有可以比较两个版本号字符串的shell脚本吗? 当你写了一个s ...
- [转]WPF——Thumb
Thumb类,表示可由用户拖动的控件.其主要三个事件分别DragDelta,DragStarted,DragCompleted. DragDelta——当 Thumb 控件具有逻辑焦点和鼠标捕获时,随 ...
- LinkedHashMap笔记
一.最基本元素存储单元 /** * HashMap.Node subclass for normal LinkedHashMap entries. */ static class Entry<K ...
- 【Uva 12128】Perfect Service
[Link]: [Description] 给你n个机器组成的一棵树,然后,让你在某些机器上安装服务器. 要求,每个机器如果没有安装服务器,都要恰好和一个安装了服务器的机器连接. 问你,最少要安装多少 ...
- springboot指定项目访问路径前缀
springboot默认的运行方式是没有项目前缀的 如果这时候我们要加上调试或者发布,可以使用下面的方法加上 方法:
- vagrant网站中box下载方法
假设需要下载Laravel/homestead这个包. 首先定位到地址:https://app.vagrantup.com/laravel/boxes/homestead/versions/8.0.0 ...
- memcache课程---4、php+memcache如何让用户跨域登录
memcache课程---4.php+memcache如何让用户跨域登录 一.总结 一句话总结: 让所有服务器共用一台memcache缓存,即可达到跨域的目的 1.session跨域:修改php配置文 ...