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(  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;
    }
收藏 打印