excel批量入数据库

作用:使用c#将同一文件夹下的全部excel,提取excel里所需内容,批量导入excess数据库
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection dbconn;
OleDbCommand cmd = null;
dbconn = new OleDbConnection(@“provider=microsoft.jet.oledb.4.0; Data Source=E:\software\WindowsFormsApplication2\db.mdb”);
DirectoryInfo folder = new DirectoryInfo(“E:\software\WindowsFormsApplication2\file”);
foreach(FileInfo file in folder.GetFiles("*.xls"))
{
DataSet dt = ExcelToDS(file.FullName);
int l = dt.Tables[0].Columns.Count;
for (int i = 0; i < l; i++)
{
dbconn.Open();
string s1 = dt.Tables[0].Columns[i].ColumnName.ToString();
string s2 = dt.Tables[0].Rows[0][i].ToString();
string sql = “insert into ************* values(’”+file.Name+"’,’" + s1 + “’,’” + s2 + “’)”;
cmd = new OleDbCommand(@sql, dbconn);
cmd.ExecuteNonQuery();
cmd.Dispose();
dbconn.Close();
}
}
this.label1.Text = “OK”;
}
public DataSet ExcelToDS(string Path)
{
string strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” + “Data Source=” + Path + “;” + “Extended Properties=Excel 8.0;”;
OleDbConnection conn2 = new OleDbConnection(strConn);
conn2.Open();
string strExcel = “”;
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = “select * from [土地总面积$3:4]”;
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, “table1”);
conn2.Close();
return ds;
}
}
}

猜你喜欢

转载自blog.csdn.net/snowfly2008/article/details/85090987