[英]Importing Excel sheet into SQL Server with C#
我正在編寫一個簡單的程序,將excel工作表導入數據庫,但是遇到以下錯誤:
找不到可安裝的ISAM
我不確定這意味着什么,經過數小時的搜索,我轉向了SO。 有很多關於Jet和ACE的討論,我不確定有什么區別,但是這里有一個摘要:我有一個稱為test或test1的excel文件,我只想導入文件中的第一張表。 到目前為止,這是我的源代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string filePath = null;
public Form1()
{
InitializeComponent();
}
//Method to check database connection
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=SSPI;";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
//Method to select a file
private void button2_Click(object sender, EventArgs e)
{
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=Excel 12.0,HDR=Yes;IMEX=1";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open(); //HERE IS WHERE THE ERROR IS
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Table";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Data Exoprted To Sql Server Succefully");
}
}
}
}
}
}
我在正確的庄園里來嗎?
您需要將連接字符串的Extended Properties
部分用引號引起來:
// here and here
// --> v v
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=""Excel 12.0,HDR=Yes;IMEX=1""";
您的計算機上可能未安裝Office oledb驅動程序。 您應該從Microsoft網站下載它。 安裝后,您的代碼應運行。
如果您正在閱讀Office 2007(或更高版本)的excel文件,那么我建議您使用開放源代碼庫Epplus來讀取excel文件。它純粹是.NET庫,因此您不會依賴oledb驅動程序。
EPPlus是一個.net庫,它使用Open Office Xml格式(xlsx)讀取和寫入Excel 2007/2010文件。
您可以使用此庫輕松地將excel文件讀入數據表。 看看這個線程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.