简体   繁体   English

C# & Excel:Value2没有定义

[英]C# & Excel: Value2 has no definition

I needed a way to read an Excel file through c#. I found an example https://coderwall.com/p/app3ya/read-excel-file-in-c我需要一种通过 c# 读取 Excel 文件的方法。我找到了一个示例https://coderwall.com/p/app3ya/read-excel-file-in-c

I created a standalone program to test it and it worked as I had expected.我创建了一个独立程序来测试它,它按我预期的那样工作。 I added the code as a subprogram into an existing program and encountered errors.我将代码作为子程序添加到现有程序中并遇到错误。

The first error, "Cannot implicitly convert type 'object' to Microsoft.Office.Interop.Excel._Worksheet. An explicit conversion exists."第一个错误,“无法将类型‘object’隐式转换为 Microsoft.Office.Interop.Excel._Worksheet。存在显式转换。”

The second error, "'Object' does not contain a definition for 'Value2'".第二个错误,“‘Object’不包含‘Value2’的定义”。

I fixed the first error with adding (Excel._Worksheet) to xlWorkbook.Sheets[1];我修复了第一个错误,将 (Excel._Worksheet) 添加到 xlWorkbook.Sheets[1];

I can't figure out the second one on Value2 and need your help: "Error 98 'object' does not contain a definition for 'Value2' and no extension method 'Value2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)"我无法弄清楚 Value2 上的第二个,需要你的帮助:“错误 98 'object' 不包含 'Value2' 的定义并且找不到接受类型为 'object' 的第一个参数的扩展方法 'Value2' (您是否缺少 using 指令或程序集引用?)”

Here's my code:这是我的代码:

using System;
using System.Collections.Generic;
using System.Collections;ArrayList, ListBox, ComboBox, etc.
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XView.Properties;
using System.Reflection;
using ZedGraph;
using System.IO;
using System.Management;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;



private void readExcelFile(ArrayList al)
    {
        string rowItems = string.Empty;

        //Create COM Objects. Create a COM object for everything that is referenced
        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"W:\acad\x-pak\XPak setting_tool_charts.xlsx");
        Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;

        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;

        //iterate over the rows and columns and print to the console as it appears in the file - Excel is not zero based!!
        //---start at i = 4 since in Rick's Excel file, that's where the data begins!
        for (int i = 4; i <= rowCount; i++)
        {
            rowItems = string.Empty;

            for (int j = 1; j <= colCount; j++)
            {
                //new line
                if (j == 1)
                    Console.Write("\r\n");

                //write the value to the console
                if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                {
                    //Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");

                    if (j == 1) //new line
                        rowItems = xlRange.Cells[i, j].Value2.ToString();
                    else
                        rowItems += "^" + xlRange.Cells[i, j].Value2.ToString();
                }
            }
            al.Add(rowItems);
        }

        //cleanup
        GC.Collect();
        GC.WaitForPendingFinalizers();

        //rule of thumb for releasing com objects:
        //  never use two dots, all COM objects must be referenced and released individually
        //  ex: [somthing].[something].[something] is bad

        //release com objects to fully kill excel process from running in the background
        Marshal.ReleaseComObject(xlRange);
        Marshal.ReleaseComObject(xlWorksheet);

        //close and release
        xlWorkbook.Close();
        Marshal.ReleaseComObject(xlWorkbook);

        //quit and release
        xlApp.Quit();
        Marshal.ReleaseComObject(xlApp);
    }

I think it is relevant to Microsoft.Office.Interop.Excel version.我认为它与 Microsoft.Office.Interop.Excel 版本有关。 I have never previously used code block following ways to solve the same mistake.我以前从未使用代码块以下方法来解决相同的错误。 I think it will work for him.我认为这对他有用。

   object _xVal;

    _xVal= ((Excel.Range)xlWorksheet.Cells[i, j]).Value2;

The cause of this problem was the Target Framework!这个问题的原因是目标框架! It was using .Net 3.5 because the main program was created in 2008. This subprogram was added today and it assumes that "Embed Interop Types = true" (Property of Reference: Microsoft.Office.Interop.Excel).它使用 .Net 3.5,因为主程序是在 2008 年创建的。这个子程序是今天添加的,它假定“嵌入互操作类型 = true”(参考属性:Microsoft.Office.Interop.Excel)。

I went to the Project Properties and set the Target Framework to ".Net Framework 4 Client Profile".我转到项目属性并将目标框架设置为“.Net Framework 4 Client Profile”。 That generated 43 errors (can't remember the error name but indicated that maybe I needed to add a reference to Microsoft.CSharp.dll).这产生了 43 个错误(不记得错误名称,但表明我可能需要添加对 Microsoft.CSharp.dll 的引用)。 I added the Microsoft.CSharp reference and all the errors disappeared!我添加了 Microsoft.CSharp 引用,所有错误都消失了!

I tried this same example tutorial and ran into the same issue.我尝试了相同的示例教程并遇到了同样的问题。 I resolved the issue in following method:我用以下方法解决了这个问题:

  1. First, create a variable like this:首先,创建一个这样的变量:

    var sno = (Excel.Range)xlWorksheet.Cells[i,1];

  2. And then access the Value2 property like this:然后像这样访问Value2属性:

    string serialno = sno.Value2.ToString();

I am using .net framework 4.5我正在使用 .net 框架 4.5

This worked for me using .net 4.8 framework (((Microsoft.Office.Interop.Excel.Range)xlRange.Cells[row, 1]).Value2.ToString());这对我有用 .net 4.8 框架 (((Microsoft.Office.Interop.Excel.Range)xlRange.Cells[row, 1]).Value2.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM