读取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表数据 导入数据库的更多相关文章
- Excel表数据导入数据库表中
***Excel表数据导入到数据库表中 通过数据库表的模板做成‘Excel’表的数据导入到数据库相应的表中(注意:主表 和 从表的关系,要先导‘主表’在导入从表) 过程:通过数据库的导入工具—先导入为 ...
- java后端服务器读取excel将数据导入数据库
使用的是easypoi,官网文档:http://easypoi.mydoc.io/ /** * 导入Excel文件 */ @PostMapping("/importTeacher" ...
- mysqlconnector将EXCEL表数据导入数据库
测试excel和脚本放在同一个目录 测试excel和脚本放在同一个目录 #!/usr/bin/env python #coding=utf-8 import xlrd import mysql.con ...
- 读取Execl表 导入数据库
不知不觉博客园园林都两年多了,我是今年毕业的应届生,最近公司项目需要改动,很多的数据需要导入,很多的实体类需要些.考虑到这些问题自己写了两个winform版的小工具,一个是读取Execl数据导入数据库 ...
- Excel表数据导入Sql Server数据库中
Excel表数据导入Sql Server数据库的方法很多,这里只是介绍了其中一种: 1.首先,我们要先在test数据库中新建一个my_test表,该表具有三个字段tid int类型, tname nv ...
- 把execel表数据导入mysql数据库
今天,是我来公司第二周的第一天. 作为新入职的实习生,目前还没适合我的实质项目工作,今天的学习任务是: 把execel表数据导入到mysql数据库,再练习下java操作JDBC. 先了解下execel ...
- C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库
C# DateTime的11种构造函数 别的也不多说没直接贴代码 using System; using System.Collections.Generic; using System.Glob ...
- Java读取Execl表格数据
在前面提到用java代码新建一个Execl 表格并添加数据到表格中, 这次写了一个读取Execl表格数据并添加导数据库中的案列 给定对方一个Execl模板表格,如果导入的Execl表格和预订的表格不相 ...
- 使用python将excel数据导入数据库
使用python将excel数据导入数据库 因为需要对数据处理,将excel数据导入到数据库,记录一下过程. 使用到的库:xlrd 和 pymysql (如果需要写到excel可以使用xlwt) 直接 ...
随机推荐
- 在Windows家里杀死一个偷端口的家伙
今天,写项目了,写了好多代码,然后运行成功,但是返回的信息啥的还有代码整体的逻辑有点问题,于是就review了代码,改了些东西,然后再次启动服务,但是,问题来了:Address already in ...
- Python开发工具,服务器框架等
python服务器框架:uWSGI WEB服务器.mod_WS.Meinheld.Gunicorn.CherryPy.Bjoern 查看python内部模块命令,内置函数,查看python已经安装的模 ...
- src或者href值为base64编码代码
大家可能注意到了,网页上有些图片的src或css背景图片的url后面跟了一大串字符,比如:data:image/png;base64, iVBORw0KGgoAAAANSUhEUgnZVJlYWR5c ...
- JavaScript push()函数追加数组数据
将数据追加到一个数组末尾的最简单的方法是通过 push() 函数. .push() 允许有一个或多个参数,并把它“push”到数组的末尾. var arr = [1,2,3];arr.push(4); ...
- 番外篇 之 Win32Api
C# 调用系统API. 从自己的软件,来操作别人写好的软件. SendMessage 句柄 标识当前进程/控件的一个标识; 本课程所用到的常量信息: private const uint LB_FI ...
- LinqProvider系列(三)如何实现自己的Linq Provider?
这篇文章将在前人的肩上,继续完成实现Linq Provider的任务. 首先,我们列出linq语法的解析过程: linq本质上就是把我们惯用的语法糖,变成了一颗表达式树,然后由不同的linq Prov ...
- 使用crontab调度任务
复杂的.分布式的.工作流式的调度可以通过azkaban来进行调度,除了执行调度任务之外,它还能进行定时调度.而对于简单的服务器任务,如执行一个小脚本,发送邮件等,可以使用crontab命令直接进行,在 ...
- 3 springboot配置文件
springboot 是习惯优于配置,抛弃SSM中繁琐的配置内容,大量的基础配置由框架的完成.所以我们现在没有用任何的配置文件,可以快速的将项目运行起来. 我们找到web模块中的application ...
- spring boot获取request
1. Controller中 1.1 通过静态方法获取 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHo ...
- 基于JSP的RSS阅读器的设计与实现
阅读器访问地址:http://easyrss.tk/,欢迎体验! 阅读导览 一. 概述 二. 设计的基本概念和原理 三. 设计方案 四. 主要源代码 五. 阅读器使用说 ...