打印本文 打印本文 关闭窗口 关闭窗口
C#从Excel导入数据到Access(C#)
作者:佚名  文章来源:本站原创  点击数1338  更新时间:2012/3/17 6:17:02  文章录入:mintao  责任编辑:mintao

这个测试是假设Excel和Access里的表Product都有NO、Height、Width、Depth、Doors5个字段。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Excel导入Access测试
{
public partial class Form1 : Form
{
string strDeleteAccess = "";
string strGetDataFromExcel = "";
string strInsertIntoAccess = "";
OleDbConnection oleDbConnAccess;
OleDbConnection oleDbConnExcel;
OleDbCommand oleDbCmdAccess;
OleDbCommand oleDbCmdExcel;
OleDbDataReader oleDbDataReaderExcel;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
oleDbConnAccess = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath.Trim() + "\\test.mdb");
oleDbConnAccess.Open();
strDeleteAccess = "delete from product ";
oleDbCmdAccess = new OleDbCommand(strDeleteAccess, oleDbConnAccess);
oleDbCmdAccess.ExecuteNonQuery();
oleDbCmdAccess.Dispose();
oleDbConnAccess.Close();

oleDbConnExcel = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=" + Application.StartupPath.Trim() +"\\test.xls");
oleDbConnExcel.Open();
strGetDataFromExcel = "SELECT * FROM [Sheet1$]";
oleDbCmdExcel = new OleDbCommand(strGetDataFromExcel, oleDbConnExcel);
oleDbDataReaderExcel = oleDbCmdExcel.ExecuteReader();
if (oleDbDataReaderExcel.HasRows == true)
{
oleDbConnAccess.Open();
for (; ; )
{
if (oleDbDataReaderExcel.Read() == true)
{
strInsertIntoAccess = "insert into news([NO],[HEIGHT],[WIDTH],[DEPTH],[DOORS]) values('" + oleDbDataReaderExcel.GetValue(0).ToString() + "','" + oleDbDataReaderExcel.GetValue(1).ToString() + "','" + oleDbDataReaderExcel.GetValue(2).ToString() + "','" + oleDbDataReaderExcel.GetValue(3).ToString() + "','" + oleDbDataReaderExcel.GetValue(4).ToString() + "') ";
oleDbCmdAccess = new OleDbCommand(strInsertIntoAccess, oleDbConnAccess);
oleDbCmdAccess.ExecuteNonQuery();
oleDbCmdAccess.Dispose();
}
else
break;
}
oleDbConnAccess.Close();
}
oleDbDataReaderExcel.Close();
oleDbCmdExcel.Dispose();
oleDbConnExcel.Close();
}
}
}


红字自己改

打印本文 打印本文 关闭窗口 关闭窗口