从 Cell 访问表并使用行和列偏移量在其中添加值
Contents
[
Hide
]
通常,您在表或列表对象中添加值使用Cell.PutValue()方法。但有时,您可能需要使用行和列偏移量在表或列表对象中添加值。
为了从单元格访问表或列表对象,使用Cell.GetTable()方法。要使用行和列偏移量在其中添加值,请使用ListObject.PutCellValue方法。
以下屏幕截图显示了代码中使用的源 Excel 文件。它包含空表并突出显示位于表内的单元格 D5。我们将从单元格 D5 使用访问此表Cell.GetTable()方法,然后使用两者添加其中的值Cell.PutValue()和ListObject.PutCellValue方法。
例子
比较源文件和输出文件的屏幕截图
![]() |
---|
以下屏幕截图显示了代码生成的输出 Excel 文件。如您所见,单元格 D5 有一个值,而位于表格偏移量 2,2 处的单元格 F6 有一个值。
![]() |
---|
C# 从单元格访问表格并使用行和列偏移量在其中添加值的代码
以下示例代码加载如上图所示的源 Excel 文件,并在表内添加值并生成如上所示的输出 Excel 文件。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create workbook from source Excel file | |
Workbook workbook = new Workbook(dataDir + "source.xlsx"); | |
// Access first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Access cell D5 which lies inside the table | |
Cell cell = worksheet.Cells["D5"]; | |
// Put value inside the cell D5 | |
cell.PutValue("D5 Data"); | |
// Access the Table from this cell | |
ListObject table = cell.GetTable(); | |
// Add some value using Row and Column Offset | |
table.PutCellValue(2, 2, "Offset [2,2]"); | |
// Save the workbook | |
workbook.Save(dataDir + "output_out.xlsx"); |