[英]c# Excel, the provider 'microsoft.ace.oledb.12.0' is not registered
I am working on a c# project where I need the user to open an Excel file and insert the data in an SQL server database.我正在处理 c# 项目,我需要用户打开 Excel 文件并将数据插入 SQL 服务器数据库。 The problem is that using this connection string
问题是使用这个连接字符串
("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;")
during the opening of the connection I get在打开连接期间我得到
the provider 'microsoft.ace.oledb.12.0' is not registered
提供程序“microsoft.ace.oledb.12.0”未注册
exception, which is odd because I worked with an Access Database and used the same connection string.异常,这很奇怪,因为我使用的是 Access 数据库并使用了相同的连接字符串。 The Access Database Engine is installed on my PC and I even compiled at x86, am I missing something?
Access 数据库引擎安装在我的 PC 上,我什至在 x86 编译,我错过了什么吗?
The reasons are as follows:原因如下:
When accessing the.xlsx file with SQL SERVER, you must use provider 'Microsoft.ACE.OLEDB.12.0' to implement.使用SQL SERVER访问.xlsx文件时,必须使用provider 'Microsoft.ACE.OLEDB.12.0'来实现。
First install AccessDatabaseEngine.exe.首先安装AccessDatabaseEngine.exe。 Download path: http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
下载路径: http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
This provider can be seen in the database on 32-bit systems.可以在 32 位系统上的数据库中看到此提供程序。
It cannot be seen in a 64-bit system, so you need to call C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe to execute the package.在64位系统是看不到的,所以需要调用C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe来执行ZEFE64B788E604A77
solution:解决方案:
Open IIS Manager.打开 IIS 管理器。
Right-click the connection pool where the application is located.右键单击应用程序所在的连接池。
Modify "Enable 32 as application" to true.将“启用 32 作为应用程序”修改为 true。
The code shown below may help you.下面显示的代码可能会对您有所帮助。
Sqlconn sqlcon = new Sqlconn();
public Form1()
{
InitializeComponent();
}
string str_Excel_Path;
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Only one file can be opened------------------------------------------
openFileDialog1.Filter = "Excel file|*.xlsx";//Set the open file filter
openFileDialog1.Title = "Open Excel file";//Set the title of the open file
openFileDialog1.Multiselect = true;//Allow multiple files to be selected
if (openFileDialog1.ShowDialog() == DialogResult.OK)//Determine whether a file is selected
{
str_Excel_Path = openFileDialog1.FileName.ToString();//Get the selected file address
textBox1.Text = str_Excel_Path;//Display the selected file address in textBox1
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string[] P_str_Names = textBox1.Text.Split(',');//Store all selected Excel file names
string P_str_Name = "";//Store the traversed Excel file name
List<string> P_list_SheetNames = new List<string>();//Create a generic collection object to store sheet names
for (int i = 0; i < P_str_Names.Length; i++)//Iterate over all selected Excel file names
{
P_str_Name = P_str_Names[i];//The Excel file name traversed by the record
P_list_SheetNames = GetSheetName(P_str_Name);//Get all sheet names in the Excel file
for (int j = 0; j < P_list_SheetNames.Count; j++)//traverse all worksheets
{
/* if (ckbox_Windows.Checked)//Log in to SQL Server with Windows authentication
//Export worksheet contents to SQL Server
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "';Initial Catalog='" + cbox_Server.Text + "';Integrated Security=True;");
}
else if (ckbox_SQL.Checked)//Log in to SQL Server with SQL Server authentication
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "'Database='" + cbox_Server.Text + "';Uid='" + txt_Name.Text + "';Pwd='" + txt_Pwd.Text + "';");
}*/
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456");
}
}
MessageBox.Show("All selected Excel sheets have been imported into SQL Server database!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select the file to be imported into the database!");
}
}
//Get all worksheet names in the Excel file
private List<string> GetSheetName(string P_str_Name)
{
List<string> P_list_SheetName = new List<string>();//Create a generic collection object
//Connect to the Excel database
//OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Name + ";Extended Properties=Excel 8.0;");
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Name + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"");
olecon.Open();//Open database connection
System.Data.DataTable DTable = olecon.GetSchema("Tables");//Create a table object
DataTableReader DTReader = new DataTableReader(DTable);//Create table read object
while (DTReader.Read())
{
string p_str_sName = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//Record the worksheet name
if (!P_list_SheetName.Contains(p_str_sName))//Determine whether the sheet name already exists in the generic collection
P_list_SheetName.Add(p_str_sName);//Add the worksheet to the pan-collection
}
DTable = null;//Clear the table object
DTReader = null;//Clear the table read object
olecon.Close();//Close the database connection
return P_list_Sheet
}
/* Import the content of the specified worksheet in Excel into the SQL Server database */
public void ImportDataToSql(string p_str_Excel, string p_str_SheetName, string p_str_SqlCon)
{
DataSet myds = new DataSet();//Create a dataset object
try
{
// get all data
//string P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_str_Excel + ";Extended Properties=Excel 8.0;";
string P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + p_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"";
OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);//Create an Oledb database connection object
string p_str_ExcelSql = "";//Record the Excel query statement to be executed
OleDbDataAdapter oledbda = null;//Create an Oledb data bridge object
p_str_ExcelSql = string.Format("select * from [{0}$]", p_str_SheetName);//Record the Excel query statement to be executed
oledbda = new OleDbDataAdapter(p_str_ExcelSql, P_str_OledbCon);//Execute Excel query using data bridge
oledbda.Fill(myds, p_str_SheetName);//Fill data
//Define variables to record the SQL statement that creates the table
string P_str_CreateSql = string.Format("create table {0}(", p_str_SheetName);
foreach (DataColumn c in myds.Tables[0].Columns)//traverse all rows in the dataset
{
P_str_CreateSql += string.Format("[{0}]text,", c.ColumnName);//Create a field in the table
}
P_str_CreateSql = P_str_CreateSql + ")";//Improve the SQL statement for creating a table
//Create SQL database connection object
using (SqlConnection sqlcon = new SqlConnection(p_str_SqlCon))
{
sqlcon.Open();//Open database connection
SqlCommand sqlcmd = sqlcon.CreateCommand();//Create an execution command object
sqlcmd.CommandText = P_str_CreateSql;//Specify the SQL data to be executed
sqlcmd.ExecuteNonQuery();//Execute operation
sqlcon.Close();//Close the database connection
}
using (SqlBulkCopy bcp = new SqlBulkCopy(p_str_SqlCon))//Import data with bcp
{
bcp.BatchSize = 100;//Number of rows per transfer
bcp.DestinationTableName = p_str_SheetName;//Define the destination table
bcp.WriteToServer(myds.Tables[0]);//Write data to SQL server data table
}
}
catch
{
MessageBox.Show("SQL Server database already exists" + p_str_SheetName + "Table!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Sqlconn code: Sqlconn 代码:
// private static string constr = "server=(local);Initial Catalog=D_total;Integrated Security=True";
private static string constr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
// private static string constr = "Data Source =192.168.1.201;Initial Catalog=D_total23 ;User Id=sa;Password=123";
public DataTable f1()
{
string A = "select name from master..sysdatabases";//Query this database information
return Only_Table1(A);
}
public DataTable Only_Table1(string exec)
{
System.Data.DataTable dt_jdl = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (con.State == ConnectionState.Open || con.State == ConnectionState.Connecting)
{
SqlDataAdapter sda2 = new SqlDataAdapter(exec, con);//All by writing stored procedures
DataSet ds2 = new DataSet();
sda2.Fill(ds2, "cxq");
dt_jdl = ds2.Tables["cxq"];
sda2.Dispose();
ds2.Dispose();
}
con.Close();
}
return dt_jdl;
}
catch (Exception EX)
{
return null;
}
}
}
Run the project:运行项目:
Click the OK button to select the xml file from the folder.单击确定按钮以 select 文件夹中的 xml 文件。 Click the import button to import the file into the database.
单击导入按钮将文件导入数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.