不知不觉博客园园林都两年多了,我是今年毕业的应届生,最近公司项目需要改动,很多的数据需要导入,很多的实体类需要些。考虑到这些问题自己写了两个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