如何将 UltraGrid 单元格中的精确值复制到 Excel

How to copy EXACT value from UltraGrid cell to Excel

我正在使用 Infragistics 的 UltraGrid 小部件创建类似 Excel 的网格。我正在尝试从单元格复制值并将其粘贴到 Excel。这工作正常,除了一个小问题:它复制单元格中显示的值 (Text 属性),而不是单元格中包含的实际值 (Value 属性).是否可以选择复制实际值而不是显示值?

我试过使用

PerformAction(UltraGridAction.Copy, false, false);

并正在寻找一些方法或方法来复制实际值,但还没有找到 none。我也尝试过实现自己的复制功能,但这会创建 CSV 数据,并且不会复制实际的单元格。

void OnExportToClipboardSelectedRows(object sender, EventArgs e)
    {
        List<UltraGridRow> rows = this.Grid.GetAllSelectedRows().ToList();
        Console.WriteLine(rows[0].Cells.Count);

        List<string> newRows = new List<string>();
        if (rows.Count > 0)
        {
            int minRowIndex = -1;
            int maxRowIndex = -1;

            foreach (var row in rows)
            {
                if (row.Index < minRowIndex || minRowIndex == -1)
                    minRowIndex = row.Index;
                if (row.Index > maxRowIndex || maxRowIndex == -1)
                    maxRowIndex = row.Index;
            }

            List<int> selectedCols = new List<int>();
            foreach (var cell in this.Grid.Selected.Cells)
            {
                if (!selectedCols.Contains(cell.Column.Index))
                    selectedCols.Add(cell.Column.Index);
            }

            for (int i = minRowIndex; i <= maxRowIndex; i++)
            {
                List<string> cells = new List<string>();
                foreach (int j in selectedCols)
                {
                    cells.Add(this.Grid.Rows[i].Cells[j].Value.ToString());
                }
                newRows.Add(String.Join("\t", cells));
            }
            Clipboard.SetText(String.Join("\n", newRows));
        }
        else
        {
            MessageBox.Show("No selected rows found.");
        }
    }

经过详尽的 trial/error 尝试,我终于找到了可行的解决方案:

var selectedCells = this.Grid.Selected.Cells;

// Loop through selected cells and put them in "edit mode" (actually, show plain text)
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.PlainText;                
}

// Execute copy command
this.Grid.PerformAction(UltraGridAction.Copy, false, false);

// Loop through selected cells and bring them back to original state
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.Default;
}

CellDisplayStyle 设置为 PlainText 时,单元格显示实际值,而不是格式化值。在该状态下,执行 Copy 和 return 细胞到原始状态。