读取Execl表 导入数据库
不知不觉博客园园林都两年多了,我是今年毕业的应届生,最近公司项目需要改动,很多的数据需要导入,很多的实体类需要些。考虑到这些问题自己写了两个winform版的小工具,一个是读取Execl数据导入数据库,另一个是自动生成实体类,以及增,删,改的方法。今天先分享Execl数据导入数据库。基本上没什么界面就两个按钮而已。一个是选择导入的文件,一个是导入数据库按钮。
首先我写了一个MSSQLAction的类,取数据的类,相当于三层里面的SqlHelper类,里面有两个方法
一个是准备读取数据前的命令配置
public static void PrepareCommand(SqlConnection conn, SqlCommand cmd, SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] value)
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cmd.Connection = conn;
if (trans != null)
{
cmd.Transaction = trans;
}
cmd.CommandText = cmdText;
cmd.CommandType = cmdType;
if (value != null)
{
foreach (SqlParameter item in value)
{
cmd.Parameters.Add(item);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
另一个就是操作增,删,改的方法
public static int ExecuteNonQuery(string connString, CommandType cmdTyep, string cmdText, params SqlParameter[] value)
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(conn, cmd, null, cmdTyep, cmdText, value);
int result = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return result;
}
}
取数据的类写好了,现在写Form的后台,一个四个方法:
一个是选择文件的事件,filepath 是一个全局变量
private void File_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.ShowDialog();
filepath = file.FileName;
label1.Text = file.FileName;
}
一个是获取Execl数据的方法
public List<System.Data.DataTable> GetExcelDatatable(string fileUrl)
{
const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
//建立连接
OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
try
{
//打开连接
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
List<System.Data.DataTable> list = new List<DataTable>();
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取Excel的第一个Sheet名称
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
System.Data.DataTable dt = new DataTable();
string sheetName = schemaTable.Rows[i]["TABLE_NAME"].ToString().Trim();
string strSql = "select * from [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dt = ds.Tables[0];
list.Add(dt);
}
return list;
}
catch (Exception exc)
{
throw exc;
}
finally
{
conn.Close();
conn.Dispose();
}
}
一个是往数据库插入数据的方法
public int InsetData(System.Data.DataTable dt)
{
int i = 0;
foreach (DataRow dr in dt.Rows)
{
string findDate = dr[0].ToString().Trim() == "" ? null :
Convert.ToDateTime(dr[0].ToString().Trim()).ToShortDateString().ToString();
string date = Convert.ToDateTime(findDate).ToString("s");
string resultDate = date.Substring(0, 10);
string brand = dr[1].ToString().Trim() == "" ? null : dr[1].ToString().Trim();
string storeName = dr[2].ToString().Trim() == "" ? null : dr[2].ToString().Trim();
string type = storeName.Substring(0, 2);
string city = dr[3].ToString().Trim() == "" ? null : dr[3].ToString().Trim();
string throughTrain = dr[4].ToString().Trim() == "" ? "0" : dr[4].ToString().Trim();
string showNumber = dr[5].ToString().Trim() == "" ? "0" : dr[5].ToString().Trim();
string payNumber = dr[6].ToString().Trim() == "" ? "0" : dr[6].ToString().Trim();
string freeNumber = dr[7].ToString().Trim() == "" ? "0" : dr[7].ToString().Trim();
string drillShow = dr[8].ToString().Trim() == "" ? "0" : dr[8].ToString().Trim();
string visitorsNumber = dr[9].ToString().Trim() == "" ? "0" : dr[9].ToString().Trim();
string commission = dr[10].ToString().Trim() == "" ? "0" : dr[10].ToString().Trim();
string activity = dr[11].ToString().Trim() == "" ? "0" : dr[11].ToString().Trim();
string other = dr[12].ToString().Trim() == "" ? "0" : dr[12].ToString().Trim();
string strConnection = "server=.;database=tests;Integrated Security=True";
string strSql = "Insert into LemonFlagshipStore(Lemon1,Lemon2,Lemon3,Lemon4,Lemon5,Lemon6,Lemon7,Lemon8,Lemon9,Lemon10,Lemon11,Lemon12,Lemon13,Lemon14) Values ('" + brand + "','" + city + "','" + resultDate + "','" + storeName + "','" + commission + "','" + activity + "','" +
throughTrain + "','" + drillShow + "','" + other + "','" + freeNumber + "','" +
payNumber + "','" + showNumber + "','" + visitorsNumber + "','" + type + "')";
int result = MSSQLAction.ExecuteNonQuery(strConnection, CommandType.Text, strSql);
i++;
}
return i;
}
最后就是一个简单点击导入数据的事件
private void Import_Click(object sender, EventArgs e)
{
try
{
List<System.Data.DataTable> table = this.GetExcelDatatable(filepath);
int listCount = 0;
foreach (System.Data.DataTable dt in table)
{
int result = this.InsetData(dt);
listCount += result;
}
MessageBox.Show("一共导入" + listCount + "数据", "导入成功");
}
catch (Exception ex)
{
MessageBox.Show("导入失败\r\n" + "失败原因为:\r\n" + ex, "提示");
}
}
基本的代码实现就这么多,当然插入要使用此代码的话自己要把数据库链接和字符串和sql的表明字段改了。做完之后是不是觉得很简单,呵呵.....
另一个改天分享。如若需要源码:QQ 2212907254
读取Execl表 导入数据库的更多相关文章
- 读取Execl表数据 导入数据库
不知不觉博客园园林都两年多了,我是今年毕业的应届生,最近公司项目需要改动,很多的数据需要导入,很多的实体类需要些.考虑到这些问题自己写了两个winform版的小工具,一个是读取Execl数据导入数据库 ...
- EXECL文件导入数据库
Execl数据导入数据库: 注意事项:execl中的列名与列数要与数据库的列名和列数一致.值类型一致,列名不一致的话可在导入的时候,给字段起别名,确定保持一致 v 界面代码: <div> ...
- C# 读取Execl和Access数据库
第一次写,请大家指教!!话不多说 直接走代码! /// <summary> /// 打开文件 /// </summary> /// <param name="s ...
- asp.net读取txt并导入数据库
源地址:http://www.cnblogs.com/hfzsjz/p/3214649.html
- 将execl里的数据批量导入数据库
本文将采用NPOI插件来读取execl文件里的数据,将数据加载到内存中的DataTable中 /// <summary> /// 将Excel转换为DataTable /// </s ...
- SpringMVC 实现POI读取Excle文件中数据导入数据库(上传)、导出数据库中数据到Excle文件中(下载)
读取Excale表返回一个集合: package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; ...
- 将数据库表导入到solr索引
将数据库表导入到solr索引 编辑solrcofnig.xml添加处理器 <requestHandler name="/dataimport" class="org ...
- Oracle 基础 导入数据库 删除用户、删除表空间、删除表空间下所有表
导入数据库 在cmd下用 imp导入 格式: imp userName/passWord file=bmp文件路径 ignore = y (忽略创建错误)full=y(导入文件中全部内容); 例: ...
- winform Execl数据 导入到数据库(SQL) 分类: WinForm C# 2014-05-09 20:52 191人阅读 评论(0) 收藏
首先,看一下我的窗体设计: 要插入的Excel表: 编码 名称 联系人 电话 省市 备注 100 100线 张三 12345678910 北京 测试 101 101线 张三 12345678910 上 ...
随机推荐
- Ubuntu中使用iptables
(一) 设置开机启动iptables # sysv-rc-conf --level 2345 iptables on (二) iptables的基本命令 1. 列出当前iptables的策略和规则 # ...
- springboot用thymeleaf模板的paginate分页
本文根据一个简单的user表为例,展示 springboot集成mybatis,再到前端分页完整代码(新手自学,不足之处欢迎纠正): 先看java部分 pom.xml 加入 <!--支持 Web ...
- Linux 下 安装jdk 1.7
Linux 下 安装jdk 1.7 参考百度经验 http://jingyan.baidu.com/album/ce09321b7c111f2bff858fea.html?picindex=6 第一步 ...
- 小明历险记:规则引擎drools教程一
小明是一家互联网公司的软件工程师,他们公司为了吸引新用户经常会搞活动,小明常常为了做活动加班加点很烦躁,这不今天呀又来了一个活动需求,我们大家一起帮他看看. 小明的烦恼 活动规则是根据用户购买订单的金 ...
- 找不到包含 OwinStartupAttribute 的程序集。 - 找不到包含 Startup 或 [AssemblyName].Startup 类的程序集。
打开web.config添加 <add key="owin:appStartup" value="false" /> <add key=&qu ...
- NYOJ 66 分数拆分
分数拆分 时间限制:3000 ms | 内存限制:65535 KB 难度:1 描述 现在输入一个正整数k,找到所有的正整数x>=y,使得1/k=1/x+1/y. 输入 第一行输入一个 ...
- 菜鸟的 Sass 学习笔记
介绍 sass 是什么?? 在sass的官网,它是这么形容给自己的 Sass is the most mature, stable, and powerful professional grade C ...
- 关于IE,Chrome,Firefox浏览器的字符串拼接问题
昨天项目测试的时候,IE8.IE11测试勾选checkbox然后执行保存的时候,竟然执行的结果与预期相反,吓屎我了,最终排查之下,原来是拼接checkbox的值的时候出现的问题.本人对js了解知之甚少 ...
- cocoa pods 命令不执行command not found
bogon:~ mrbtios01$ cd Desktop/改版app/lingMoney新改版的 //当出现如下问题时: bogon:lingMoney新改版的 mrbtios01$ vim pod ...
- cache buffer
//本文基本上是摘要了网络上各位大神对cache.buffer的总结,由于是800年前保存在本地,所以也已经忘了出处了.感谢各位大神. //本文对这2个概念的理解尚浅,如果愿意补充那就再好不过了. ...