读取SSIS脚本任务中的Excel单元格值时出现OleDbException



我有一个SSIS包,我在其中读取Excel文件并将数据加载到SQL表中。读取Excel文件的一部分是检查每个工作表中特定单元格中的值,并确保该值与工作表名称匹配。我在脚本任务中有以下代码(这不是所有的代码,只是错误发生的相关部分(:

public void Main()
{
//Declare and initialize variables
String FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
String FilePath = Dts.Variables["User::FolderPath"].Value.ToString() + Dts.Variables["User::strCurrentFileIn"].Value.ToString();
String TableName = Dts.Variables["User::TableName"].Value.ToString();
String SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
String CellToRead = Dts.Variables["User::CellToRead"].Value.ToString();
String CellName = "";
Int32 CellNumber;

var directory = new DirectoryInfo(FolderPath);
FileInfo files = new FileInfo(FilePath);
String FileLoaddate;

ConnectionManager cm;
SqlConnection myADONetConnection;
SqlCommand cmd;

cm = Dts.Connections["CP_RACO_ADO"];
myADONetConnection = (SqlConnection)cm.AcquireConnection(Dts.Transaction);

int intIndex = 1;

var alphanumericstring = new System.Text.RegularExpressions.Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = alphanumericstring.Match(CellToRead);
CellName = match.Groups["Alpha"].Value;
int.TryParse(match.Groups["Numeric"].Value, out CellNumber);

//Process current inbound file
FileLoaddate = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");

//Create Excel Connection
string ConStr;
string LoadingFilename = files.Name;
string HDR;
HDR = "NO";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="" + FilePath + "";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=1"";
OleDbConnection cnn = new OleDbConnection(ConStr);

////Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
string ldsheetname = "";

//Get Row Count for each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
ldsheetname = sheetname.Replace("$", "");
ldsheetname = ldsheetname.Replace("'", "");
ldsheetname = ldsheetname.Replace(" ", "");

//Read the cell value from Excel sheet
OleDbCommand oCell = new OleDbCommand("select  * from [" + sheetname + CellName + (CellNumber - 1).ToString() + ":" + CellToRead + "]", cnn);
OleDbDataAdapter daCell = new OleDbDataAdapter(oCell);
DataTable dtCell = new DataTable();
daCell.Fill(dtCell);

一切都很好,直到daCell.Fill(dtCell(语句。此时,脚本抛出以下错误:

System.Data.OleDb.OleDbException:Microsoft Access数据库引擎找不到对象"BETTAREL,BRIAN J$'B8:B9"。制作确保对象存在,并拼写其名称和路径名正确地

在本节之后不久,就是将所有Excel数据实际加载到表中的代码,该部分工作正常。那么,为什么一次加载一整张表可以工作,但我不能读取单个单元格的值呢?是什么导致了这个错误,我该如何解决这个问题?我试着添加了一个感叹号(就像你在Excel公式中看到的那样(,但没有成功。我试过去掉美元符号,但没用。我试过用替换来去掉引号,但没有用。

这是由某种原因造成的,再多的谷歌搜索或篡改代码似乎都不起作用。有人知道为什么会发生这种情况,和/或我需要做什么才能让它发挥作用吗?

在这里找到了答案。工作表名称中有单引号,当我去掉引号时,我去掉了双引号。删除单引号起作用了,代码现在也起作用了。

相关内容

最新更新