Skip to main content

How to: Copy Cell Data Only, Cell Style Only, or Cell Data with Style

  • 3 minutes to read

This example demonstrates how to copy data from one cell to another, and specify which parts of the copied data (for example, value only, formatting information only, borders only, etc.) should be pasted into the destination cell. To do this, call the CellRange.CopyFrom method of the Cell object corresponding to the cell into which you want to copy data from another cell. Pass the source cell object and required member of the PasteSpecial enumerator as parameters.

View Example

Worksheet worksheet = workbook.Worksheets[0];
worksheet.Columns["A"].WidthInCharacters = 32;
worksheet.Columns["B"].WidthInCharacters = 20;
Style style = workbook.Styles[BuiltInStyleId.Input];

// Specify the content and formatting for a source cell.
worksheet.Cells["A1"].Value = "Source Cell";

Cell sourceCell = worksheet.Cells["B1"];
sourceCell.Formula = "= PI()";
sourceCell.NumberFormat = "0.0000";
sourceCell.Style = style;
sourceCell.Font.Color = Color.Blue;
sourceCell.Font.Bold = true;
sourceCell.Borders.SetOutsideBorders(Color.Black, BorderLineStyle.Thin);

// Copy all information from the source cell to the "B3" cell. 
worksheet.Cells["A3"].Value = "Copy All";
worksheet.Cells["B3"].CopyFrom(sourceCell);

// Copy only the source cell content (e.g., text, numbers, formula calculated values) to the "B4" cell.
worksheet.Cells["A4"].Value = "Copy Values";
worksheet.Cells["B4"].CopyFrom(sourceCell, PasteSpecial.Values);

// Copy the source cell content (e.g., text, numbers, formula calculated values) 
// and number formats to the "B5" cell.
worksheet.Cells["A5"].Value = "Copy Values and Number Formats";
worksheet.Cells["B5"].CopyFrom(sourceCell, PasteSpecial.Values | PasteSpecial.NumberFormats);

// Copy only the formatting information from the source cell to the "B6" cell.
worksheet.Cells["A6"].Value = "Copy Formats";
worksheet.Cells["B6"].CopyFrom(sourceCell, PasteSpecial.Formats);

// Copy all information from the source cell to the "B7" cell except for border settings.
worksheet.Cells["A7"].Value = "Copy All Except Borders";
worksheet.Cells["B7"].CopyFrom(sourceCell, PasteSpecial.All & ~PasteSpecial.Borders);

// Copy information only about borders from the source cell to the "B8" cell.
worksheet.Cells["A8"].Value = "Copy Borders";
worksheet.Cells["B8"].CopyFrom(sourceCell, PasteSpecial.Borders);

The image below shows how different parts of cell data can be copied and pasted into other cells.

SpreadsheetControl_CellCopy