gpt4 book ai didi

c# - 使用 Interop c# 在 Microsoft Excel 中检测数据透视表

转载 作者:太空狗 更新时间:2023-10-30 00:39:25 24 4
gpt4 key购买 nike

我正在尝试使用 Microsoft Interop c# 检测 Microsoft excel 中的单元格是否包含数据透视表

我想要做的是按照下面的代码所示遍历所有单元格,然后如果单元格包含数据透视表,我想将该单元格的行和列信息存储在一个整数值中:

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

Excel.Range cell = null;

for (int iRow = 1; iRow < rowCount; iRow++)
{
for (int iCol = 1; iCol <= colCount; iCol++)
{
/* This line of code is probably wrong */
cell = xlRange.Cells[iRow, iCol] as Excel.Range;

if(/*Cell contains PivotTable*/)
{
int rowLocation = iRow;
int colLocation = iCol;
}
}
}

我试过查看 MSDN和其他来源,但似乎找不到任何方法来检测单元格是否包含数据透视表。

感谢任何帮助,谢谢。

最佳答案

这里有一些代码供引用。识别工作表中数据透视表占用的整体范围,并验证单元格是否是范围的一部分。

private Excel.Range IdentifyPivotRanges(Excel.Range xlRange)
{
Excel.Range pivotRanges = null;
Excel.PivotTables pivotTables = xlRange.Worksheet.PivotTables();
int pivotCount = pivotTables.Count;
for (int i = 1; i <= pivotCount; i++)
{
Excel.Range tmpRange = xlRange.Worksheet.PivotTables(i).TableRange2;
if (pivotRanges == null) pivotRanges = tmpRange;
pivotRanges = this.Application.Union(pivotRanges, tmpRange);
}
return pivotRanges;
}

private void CheckCellsForPivot(Excel.Range xlRange)
{
Excel.Range pivotRange = IdentifyPivotRanges(xlRange);
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int iRow = 1; iRow <= rowCount; iRow++)
{
for (int iCol = 1; iCol <= colCount; iCol++)
{
var cell = xlRange.Cells[iRow, iCol];
if (Application.Intersect(pivotRange, cell) != null)
{
int rowLocation = iRow;
int colLocation = iCol;
}
}
}
}

关于c# - 使用 Interop c# 在 Microsoft Excel 中检测数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35623752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com