Npoi将excel数据导入到sqlserver数据库
/// <summary>
/// 将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <returns>返回datatable</returns>
DataTable ExcelTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = ;
public bool ExcelToDataTable(string filePath)
{ try
{
using (fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// 解决版本兼容
//07以前为xls,以后为xlsx
if (filePath.IndexOf(".xlsx") > )
{
workbook = new XSSFWorkbook(fs);
}
else if (filePath.IndexOf(".xls") > )
{
workbook = new HSSFWorkbook(fs);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt();//读取第一个sheet
ExcelTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > )
{
IRow firstRow = sheet.GetRow();//第二行
int cellCount = firstRow.LastCellNum;//列数
//创建datatable的列
startRow = ;//因为第一行是中文列名所以直接从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
ExcelTable.Columns.Add(column);
}
}
} //填充datatable行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue; dataRow = ExcelTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式的处理
if (format == || format == || format == || format == )
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
} ExcelTable.Rows.Add(dataRow); }
}
}
}
}
//由于excel表在删除一张表的时候回再次读取回出现空行的原因
//所以需要一个删除空行的方法⇣⇣⇣⇣
List<DataRow> removelist = new List<DataRow>();
for (int i = ; i < ExcelTable.Rows.Count; i++)
{
bool IsNull = true;
for (int j = ; j < ExcelTable.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(ExcelTable.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(ExcelTable.Rows[i]);
}
}
for (int i = ; i < removelist.Count; i++)
{
ExcelTable.Rows.Remove(removelist[i]);
}
removelist.Clear();
//遍历将datatable内的值存入数据库
foreach (DataRow item in ExcelTable.Rows)
{ RT_Community com = new Model.RT_Community();
RT_UserInfo userinfo = new Model.RT_UserInfo();
Guid guid = Guid.NewGuid();
Guid guidu = Guid.NewGuid();
int aid = GetVpnUserName(item[].ToString());
int query = ; using (var conn = PublicMethod.GetSqlConnection())
{
//当小区名称存在时会返回-1
query = conn.Execute(@"IF NOT EXISTS
(SELECT Name FROM RT_Community WHERE Name=@Name )
INSERT INTO RT_Community
(Id,VpnUser_id,Name,Sabb,PropertyName,PropertyUserName,PropertyPhone,Address,IsDelete) values
(@Id,@VpnUser_id,@Name,@Sabb,@PropertyName,@PropertyUserName,@PropertyPhone,@Address,@IsDelete)",
new {
Id = guid,
VpnUser_id = aid,
Name = item[].ToString(),
Sabb = ChinesePinYin.GetSpellCode(item[].ToString()),
PropertyName = item[].ToString(),
PropertyUserName = item[].ToString(),
PropertyPhone = item[].ToString(),
Address = item[].ToString(),
IsDelete = ,
});
}
//当返回-1时调用查询小区id的方法对guid重新赋值
if (query == -)
{
guid = GetComId(item[].ToString());
if (guid.ToString() == "00000000-0000-0000-0000-000000000000")
{
//当返回的guid为0时
return false;
}
}
using (var conn = PublicMethod.GetSqlConnection())
{
var result = conn.Execute(@"INSERT INTO RT_UserInfo
(Id,
rt_community_id,
UserCode,
Name,
BuildingNo,
UnitNo,
Floor,
HouseNo,
Address,
HeatType,
Location,
Phone,
IsDelete) VALUES
(@Id,
@rt_community_id,
@UserCode,
@Name,
@BuildingNo,
@UnitNo,
@Floor,
@HouseNo,
@Address,
@HeatType,
@Location,
@Phone,
@IsDelete)",
new
{ Id = guidu,
rt_community_id = guid,
UserCode = item[].ToString(),
Name = item[].ToString(),
BuildingNo = item[].ToString(),
UnitNo = item[].ToString(),
Floor = item[].ToString(),
HouseNo = item[].ToString(),
Location = item[].ToString(),
Address = item[].ToString(),
HeatType = ,
Phone = item[].ToString(),
IsDelete =
});
} }
//成功返回true
return true;
}
catch (Exception)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
//使用时直接用nuget包搜索nopi第一个导入这样就全装好了简单又省事
Npoi将excel数据导入到sqlserver数据库的更多相关文章
- Excel 数据导入至Sqlserver 数据库中 ltrim() 、rtrim() 、replace() 函数 依次空格无效问题
今天导一些数据从Excel中至Sqlserver 数据库中,在做数据合并去重的时候发现,有两条数据一模一样,竟然没有进行合并: 最后发现有一条后面有个“空格”,正是因为这个“空格”让我抓狂许久,因为它 ...
- EXCEL批量导入到Sqlserver数据库并进行两表间数据的批量修改
Excel 大量数据导入到sqlserver生成临时表并将临时表某字段的数据批量更新的原表中的某个字段 1:首先要对EXCEL进行处理 列名改成英文,不要有多余的列和行(通过ctrl+shift 左或 ...
- excel数据导入到sqlserver中---------工作笔记
调用页面: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sys ...
- Excel表格数据导入到SQLServer数据库
转载:http://blog.csdn.net/lishuangzhe7047/article/details/8797416 步骤: 1,选择要插入的数据库--右键--任务--导入数据 2,点击下一 ...
- 将Excel文件数据导入到SqlServer数据库的三种方案
方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server,这种方法的优点是非常的灵活,可以对Excel表中的各个单元格进行用户所需的操作. openFil ...
- 使用navicat for sqlserver 把excel中的数据导入到sqlserver数据库
以前记得使用excel向mysql中导入过数据,今天使用excel向sqlserver2005导入了数据,在此把做法记录一下 第一步:准备excel数据,在这个excel中有3个sheet,每个she ...
- c# excel如何导入到sqlserver数据库
最近在做这个如何把excel导入到数据库中,经过多方查找,终于找到一个适合的,并且经过自己的完善可以正常使用(忘记原作者博客的链接地址了,敬请见谅) 首先是窗体的创建,文本框显示文件的路径,按钮执行操 ...
- 基于NPOI的Excel数据导入
从Excel导入数据最令人头疼的是数据格式的兼容性,特别是日期类型的兼容性.为了能够无脑导入日期,折腾了一天的NPOI.在经过测试确实可以导入任意格式的合法日期后,写下这篇小文,与大家共享.完整代码请 ...
- 简单的将Excel数据同步到SqlServer数据库中
1.创建一个WinForm程序,添加一个Button控件 2.Button事件 private void button1_Click(object sender, EventArgs e) { Sys ...
随机推荐
- ExtJS动态创建组件
J是代码动态创建dom: 或者 eval有后台组织代码,前台执 ======================= ExtJS组件的动态的创建: 程序中大多数时候需要在后台根据业务逻辑创建符合要求的组件, ...
- python twilio 短信群发 知识留存
1. win7 32位系统,傻瓜安装Anaconda2(python 2.7) 2. 打开cmd, 输入命令pip install twilio,在线安装twilio 3. 打开Anaconda2的S ...
- thinkphp5中Indirect modification of overloaded element of XXX has no effect的解决办法
最近在使用Thinkphp5做foreach循环嵌套的时候报错:Indirect modification of overloaded element of XXX has no effect,网上搜 ...
- MultipartFile 转换为File
选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 . MultipartFile multipartFile; File fil ...
- 跟我学算法-tensorflow 实现卷积神经网络
我们采用的卷积神经网络是两层卷积层,两层池化层和两层全连接层 我们使用的数据是mnist数据,数据训练集的数据是50000*28*28*1 因为是黑白照片,所以通道数是1 第一次卷积采用64个filt ...
- 小学生福利V2.0.1
211606320刘佳&211506332熊哲琛 一.预估与实际 PSP2.1 Personal Software Process Stages 预估耗时(分钟) 实际耗时(分钟) Plann ...
- python安装h5py
sudo pip install cython sudo apt-get install libhdf5-dev sudo pip install h5py test: python import h ...
- Python3 hex() 函数
Python3 hex() 函数 Python3 内置函数 描述 hex() 函数用于将一个指定数字转换为 16 进制数. 语法 hex 语法: hex(x) 参数说明: x -- 一个整数 返回值 ...
- Cocoa Touch(四): 多线程GCD, NSObject, NSThread, NSOperationQueue
多线程的重要性不必多言,现代操作系统不可能离开进程线程的抽象.具体到ios应用,我们只能在一个进程中管理线程,主线程不应该去执行非常耗时间的后台操作导致出现卡机现象,后台的事情交给后台线程来完成. G ...
- react-native 打包 出apk
先上步骤: 一. 生成签名文件(my-release-key.keystore文件) Android要求所有应用都有一个数字签名才会被允许安装在用户手机上 1. 在项目目录下运行如下命令: keyt ...