C# ETL脚本-';对象';不包含';价值';在Microsoft.Office.Interop中

C# ETL脚本-';对象';不包含';价值';在Microsoft.Office.Interop中,c#,excel,.net-3.5,.net-4.5,etl,C#,Excel,.net 3.5,.net 4.5,Etl,我有一个.NET4.5项目,从Excel文件中获取数据,并将其中一些保存到文件中。它运行得很好 然而,我决定进行一个ETL过程,运行这个脚本,然后将其上传到数据库。在ETL过程的脚本任务中,我只是简单地将相同的代码粘贴到窗口,添加相同的引用等,然后得到一个bug:“object”不包含“Value”的定义 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; usin

我有一个.NET4.5项目,从Excel文件中获取数据,并将其中一些保存到文件中。它运行得很好

然而,我决定进行一个ETL过程,运行这个脚本,然后将其上传到数据库。在ETL过程的脚本任务中,我只是简单地将相同的代码粘贴到窗口,添加相同的引用等,然后得到一个bug:“object”不包含“Value”的定义

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

namespace etl.csproj
{
        public void Main()
        {
            process();
            Dts.TaskResult = (int)ScriptResults.Success;
        }

        static void process()
        {
            string mySheet = @"C:\\pathToMyExcelFile";
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\my file.txt");
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook xlWorkBook = excelApp.Workbooks.Open(mySheet, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel.Sheets sheets = xlWorkBook.Worksheets;
            Excel.Worksheet worksheet;

            for (int i = 1; i < sheets.Count; ++i)
            {
                worksheet = (Excel.Worksheet)sheets.get_Item(i);
                for (int j = 5; j <= 9; ++j)
                {
                    for (int k = 68; k <= 72; k++)
                    {

                        if (worksheet.Cells[k, j].Value2 != null) //HERE IS THE ERROR
                        {
                            file.WriteLine(worksheet.Name + "|" + (string)(worksheet.Cells[k, 2] as Excel.Range).Value /*ERROR HERE*/ + "|" + (j - 4).ToString() + "|" + worksheet.Cells[k, j].Text/*ERROR HERE*/);
                        }
                    }


                }

            }
            file.Close();
        }

    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用Microsoft.Office.Interop;
使用Excel=Microsoft.Office.Interop.Excel;
命名空间etl.csproj
{
公共图书馆
{
过程();
Dts.TaskResult=(int)ScriptResults.Success;
}
静态空洞过程()
{
字符串mySheet=@“C:\\pathToMyExcelFile”;
System.IO.StreamWriter file=new System.IO.StreamWriter(@“C:\my file.txt”);
Excel.Application excelApp=新的Excel.Application();
Excel.Workbook xlWorkBook=excelApp.Workbooks.Open(mySheet,0,true,5,“,”,true,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,“\t”,false,false,0,true,1,0);
Excel.Sheets=xlWorkBook.Worksheets;
Excel.工作表;
对于(int i=1;ifor(int j=5;j.NET 4.0使这样的COM编程变得容易多了。这主要归功于C#version 4中添加的dynamic关键字。在3.5中没有这一点,工作表。单元格[k,j]是对象,而不是动态的。因此,您必须自己转换为(范围)。@HansPassant您能在回答中提供代码吗?