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

时间:2017-03-28 08:36:32

标签: c# infragistics

我正在使用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.");
        }
    }

1 个答案:

答案 0 :(得分:2)

经过详尽的试验/错误尝试后,我终于找到了解决方案:

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