使用 C# 访问 Excel 单元格

现在只想能够访问一个 excel 单元格值并在我的控制台窗口中打印该值。


我尝试过的其他一些方法:


System.Console.WriteLine(Mysheets.Cells[1,1].Tostring);

请注意,上面的方法,在括号智能感知之后点击句点后,只给了我等于、gethashcode、获取类型或两个字符串的选项。我在括号后看到了一些调用 .value 但我没有选择这样做。


using Excel = Microsoft.Office.Interop.Excel;


class Program

{

    private static Excel.Workbook MyBook = null;

    private static Excel.Application MyApp = null;

    private static Excel.Worksheet MySheet = null;

    private static Excel.Range MyRangeOne = null;


    public static void Main()

    {

        string path = @"Z:\New folder\Test1234.xlsx";

        MyApp = new Excel.Application();

        MyApp.Visible = true;

        MyBook = MyApp.Workbooks.Open(path);

        MySheet = (Excel.Worksheet)MyBook.Worksheets[1];

        MyRangeOne = (Excel.Range)MySheet.Cells[1,1];


        try {

            System.Console.WriteLine(MySheet.Name);

            System.Console.WriteLine(MyRangeOne.Value);

        }

        catch(System.Exception err){

            System.Console.WriteLine(err.Message);

        }

    }

}

也试过


=Myrangeone.item[1,1].value. Keep getting the following error:

你调用的对象是空的


令人惊讶的是,这是多么困难。


慕标琳琳
浏览 165回答 1
1回答

扬帆大鱼

我建议您将此库用于 Excel 工作表处理EPPlus。您处理 Excel 文件的方式效率不高。所以请在这里查看。这个库可以通过 NuGet 包管理器安装。这是非常容易使用。
打开App,查看更多内容
随时随地看视频慕课网APP