有没有一种使用C#模仿Excel中格式刷的方法?

3
我正在编写一个C#程序,使用Microsoft.Office.Interop.Excel操作几个Excel文件(xls格式)。我的需求是添加一个新的工作表并写入一些数据,其格式与现有工作表中的数据类似。因此,我需要找到一种方法来执行像手动修改Excel文件时的“格式刷”操作。我的意思是,我需要设置数字格式、背景颜色、字体、字体颜色、对齐方式等等。
我尝试通过在需要修改的单元格中设置NumberFormat和Style属性来实现这一点。代码如下:
newSheet.Cells[6, 3].Value2 = 10;
newSheet.Cells[6, 3].NumberFormat = existingSheet.Cells[5, 4].NumberFormat;
newSheet.Cells[6, 3].Style = existingSheet.Cells[5, 4].Style;

根据我的观察,NumberFormat 已经没问题了(我已经通过这样做正确地设置了日期、百分比和其他数字格式)。但是背景颜色、字体和字体颜色等内容没有按照预期更改。那么该怎么办呢?谢谢!

1个回答

2
尝试使用CopyPasteSpecial方法。
  1. 复制单元格的所有内容。源单元格具有预期的格式。在您的代码中,它是单元格Cells[5, 4]

  2. 仅将格式粘贴到目标单元格。在您的代码中,它是单元格Cells[6, 3]

示例:

Microsoft.Office.Interop.Excel.Range source = existingSheet.Cells[5, 4];
source.Copy(); // Copy everything from the source cell to the clipboard

Microsoft.Office.Interop.Excel.Range target = newSheet.Cells[6, 3];
target.Value = 456; // Write value to the target cell and ...
target.PasteSpecial(XlPasteType.xlPasteFormats); // Paste only formats from the source cell

谢谢。这正是我在寻找的! - tete

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接