【问题标题】:How to access an Excel WorkSheet cell in c#如何在 C# 中访问 Excel 工作表单元格
【发布时间】:2014-09-11 16:36:04
【问题描述】:

我在 C# 中使用 Microsoft.Office.Interop.Excel 命名空间来访问 Excel 工作表。

我在访问工作表中的特定单元格时遇到了一些问题。

这是我目前所拥有的:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input.Manipulations;
using Application = Microsoft.Office.Interop.Excel.Application;




namespace excelProgram
{
    class Program
    {
        [STAThreadAttribute]
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.openWorkSheet();
            Console.ReadKey(true);
        }


        private void openWorkSheet()
        {
            var xl= new Application();
            xl.Visible = true;
            xl.Workbooks.Open(@"C:\Documents and Settings\user\Desktop\Book1.xls");

        }


    }
}

我创建了一个Application() 对象,它可以在我的 PC 上打开一个 Excel 工作簿。这很好用,但是我不知道如何访问工作簿中工作表中的特定单元格,例如单元格 B1。

有人可以帮忙吗?

【问题讨论】:

  • xl.Workbooks.Open(...) 命令是否返回工作簿?
  • @Gwny 是的,它会打开实际的 Excel 工作簿。
  • 您可以尝试通过 Range 访问它: Range aRange = Workbook.get_Range("C1", "C7");

标签: c# excel


【解决方案1】:

获取对特定工作表的引用,然后是特定范围,例如像这样。

(示例使用对 Excel 2007 PIA 的引用:C:\Windows\assembly\GAC\Microsoft.Office.Interop.Excel\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll)

using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using Excel = Microsoft.Office.Interop.Excel;

Application excelApplication = new Excel.Application
{
    Visible = true,
    ScreenUpdating = true
};

_Workbook workbook = excelApplication.Workbooks.Open(@"C:\Temp\Book1.xlsx");
_Worksheet sheet = workbook.Worksheets[1];
Range range = sheet.Range["B1"];
range.Formula = "Test";

excelApplication.Quit();

【讨论】:

  • 这工作,除非我必须显式类型转换工作表,如 _Worksheet sheet = (Worksheet)workbook.Worksheets[1]; 否则会给出编译器错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多