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



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

我试过使用

PerformAction(UltraGridAction.Copy, false, false);

并寻找一些复制真实值的方法或方式,但没有找到。我也尝试实现我自己的复制功能,但这会创建 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.");
        }
    }

经过详尽的试错尝试,我终于找到了工作解决方案:

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并将单元格返回到原始状态。

最新更新