我在 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。
有人能帮忙吗?
最佳答案
获取对特定工作表的引用,然后对特定范围进行引用,例如像这样。
(示例使用对 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();
关于c# - 如何在 C# 中访问 Excel 工作表单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25765529/