gpt4 book ai didi

c# - 尝试连接到 C# 中的 Excel 电子表格

转载 作者:行者123 更新时间:2023-11-30 21:04:07 24 4
gpt4 key购买 nike

我正在尝试从电子表格中提取大量数据,但无法在我的 C# 代码中成功建立连接。 B

下面是连接字符串和我用来建立连接的代码。该程序的目标是从电子表格中提取数据并将其存入 SQL 数据库。我无法通过 connection.open() 命令,但是没有收到此错误消息:

“外部表不是预期的格式”

        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{

OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();


while (reader.Read())
{
counter++;

//Access db values
string compCode = "";
string agId = "";
string fName = "";
string lName = "";
string nameSuffix = "";


compCode = reader.GetValue(0).ToString();
agId = reader.GetString(1);
fName = reader.GetString(2);
lName = reader.GetString(3);
nameSuffix = reader.GetString(4);

sqlComm.Parameters.Add(companyCode);
sqlComm.Parameters.Add(agentID);
sqlComm.Parameters.Add(firstName);
sqlComm.Parameters.Add(lastName);
sqlComm.Parameters.Add(suffix);

//Initialize connection objects
cm = Dts.Connections["QUAHILSQ03"];
sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;

//Execute stored procedure
sqlComm.ExecuteNonQuery();

}
reader.Close();
connection.Close();
OleDbConnection.ReleaseObjectPool();
}

最佳答案

对于 *.xlsx,您需要 Ace 驱动程序:Microsoft.ACE.OLEDB.12.0

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";

关于c# - 尝试连接到 C# 中的 Excel 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com