请问如何抓取某窗口内控件类型为DataGrid的全部表单文本?

使用问题 · 467 次浏览
蓝雪人 创建于 2023-03-04 14:28

请问如何抓取某窗口内控件类型为DataGrid的全部表单文本?难道只有对DataGrid控件内的值一个一个抓取么?

比如软件内表单数据的控件XPATH是/Custom[2]/DataGrid,单个表单文本的xpath为/Custom[2]/DataGrid/DataItem[x]/Custom[x]

DataGrid控件内有几百个表单文本,而且每隔10秒数据刷新,如果单个循环抓取效率太慢了

蓝雪人 最后更新于 2023/3/4

回复内容
CL 2023-03-04 19:48
#1

如果能访问到数据源,如数据库或API请求,是最理想不过的。如果通过Quicker,有点麻烦,这里是Bing给出的思路。


您好,这是 Bing。😊

我为您生成了一段 C# 代码,但是我不能保证它的正确性和完整性。您可以根据您的具体需求进行修改和测试。

using System;
using System.Windows.Automation;
using Excel = Microsoft.Office.Interop.Excel;

namespace UIAutomationDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取 DataGrid 控件的 AutomationElement 对象
            AutomationElement dataGrid = AutomationElement.RootElement.FindFirst(TreeScope.Descendants,
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataGrid));

            // 创建 excel 应用程序对象
            Excel.Application excelApp = new Excel.Application();
            // 创建 excel 工作簿对象
            Excel.Workbook workbook = excelApp.Workbooks.Add();
            // 创建 excel 工作表对象
            Excel.Worksheet worksheet = workbook.Sheets[1];

            // 获取 DataGrid 的行数和列数
            int rowCount = dataGrid.Current.RowCount;
            int columnCount = dataGrid.Current.ColumnCount;

            // 遍历 DataGrid 的每个单元格,并将其值写入到 excel 表格中
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    // 获取单元格的 AutomationElement 对象
                    AutomationElement cell = dataGrid.FindFirst(TreeScope.Children,
                        new PropertyCondition(AutomationElement.NameProperty, $"Row {i}, Column {j}"));
                    // 获取单元格的值属性
                    string value = cell.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty) as string;
                    // 将值写入到 excel 表格中对应的单元格中
                    worksheet.Cells[i + 1, j + 1] = value;
                }
            }

            // 保存 excel 文件到指定路径
            workbook.SaveAs(@"C:\Users\user\Desktop\data.xlsx");
            
        }
    }
}
回复主贴