将Excel数据表导入到SQL中成为mdf数据库文件
建一个C#应用程序,在界面添加一个按钮,建一个数据库Library,设置xls文件相应路径,设置数据库服务器名,即可。
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = @"D:\";//初始路径的设置,作相应修改
openFileDialog.Filter = "Excel files(*.xls)|*.xls";
SqlConnection sqlConnection1 = null;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
sqlConnection1 = new SqlConnection();
//将Data
Source项的值设置为本机数据库服务器,DATABASE项设置为要导入的xls文件的路径
sqlConnection1.ConnectionString = "Data
Source=WIN-8B6N9PBB3FD\\SQLEXPRESSES;Initial
Catalog=Library;Integrated Security=True";
string exportSQL = @"select * into Library from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel
5.0;HDR=YES;DATABASE=d:\axx.xls',sheet1$)";
try
{
sqlConnection1.Open();
SqlCommand sqlCommand2 = new SqlCommand();
sqlCommand2.Connection = sqlConnection1;
sqlCommand2.CommandText = exportSQL;
sqlCommand2.ExecuteNonQuery();
MessageBox.Show("export finish!");
}
catch (Exception ex)
{