c# - 在 SSIS 中访问 C# 中的 Excel 单元格
问题描述
我正在尝试访问 SSISscript
代码中的 excel 单元格。
我已经看过并用谷歌搜索并尝试过但停在了这个error
。
我设法获得了 excel 表格,但无法获得一张表格来读取其单元格:
public void Main()
{
// TODO: Add your code here
string path = Dts.Variables["User::SourceFile"].Value.ToString();
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Open(path);
//Worksheet excelSheet = wb.ActiveSheet;
Sheets Shts = excel.Worksheets;
// ERROR HERE
Worksheet sh = (Worksheet) Shts.get_Item("Sheet2");
//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
wb.Close();
MessageBox.Show(test);
Dts.TaskResult = (int)ScriptResults.Success;
}
为什么这条线给了我一个error
:
Worksheet sh = (Worksheet) Shts.get_Item("Sheet2");
获取单元格数据的正确方法是什么?
解决方案
在您的代码中:
Workbook wb = excel.Workbooks.Open(path);
Sheets Shts = excel.Worksheets;
// ERROR HERE
Worksheet sh = (Worksheet) Shts.get_Item("Sheet2");
我认为应该是:
Workbook wb = excel.Workbooks.Open(path);
Sheets Shts = wb.Worksheets; //The WorkBook contains Sheets, not the parent object Excel
var sheet = Shts[1] as Excel.Worksheet;
推荐阅读
- docker - 用于 dotnet core 2.1 和 IIS 的 Docker 映像
- javascript - 如何在反应js中的对象数组中添加一个对象
- amazon-web-services - 使用 Grunt 部署到 AWS Lambda
- r - 在 R 中查找数据帧的有效方法
- javascript - 将 Jquery 代码正确集成到 mvc 核心项目中
- javascript - 带有 select2 自动完成功能的 Rails 嵌套表单
- postman - CppRest GET 不接收正文?
- c# - wpf根据xaml中另一个元素的子项计数隐藏一个元素
- wpf - 如何在保持居中的同时将视图调整到最大限制
- haskell - Haskell 线性搜索(返回索引)