首页 > 解决方案 > 在 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");

获取单元格数据的正确方法是什么?

标签: c#excelssis

解决方案


在您的代码中:

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;

推荐阅读