Created
November 29, 2019 10:56
-
-
Save mpfund/75638a7e7c090293b65fc7d42b72ddba to your computer and use it in GitHub Desktop.
format character in excel cell and preserve old formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Office.Interop.Excel; | |
using System; | |
using System.Collections.Generic; | |
using System.Drawing; | |
namespace excelinterop | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var app = new Application(); | |
app.Visible = true; | |
var myBook = app.Workbooks.Open(@"c:\temp\test.xlsx"); | |
var mySheet = (Worksheet)myBook.Worksheets[1]; | |
Console.WriteLine("sheet " + mySheet.Name); | |
var cell = mySheet.Cells[1, 1] as Microsoft.Office.Interop.Excel.Range; | |
Console.WriteLine("cell " + cell.Value); | |
var colors = ReadColor(cell); | |
AddText(cell, colors, "abc", Color.DarkRed); | |
} | |
private static void AddText(Microsoft.Office.Interop.Excel.Range cell, List<double> colors, string v, Color color) | |
{ | |
cell.Value2 += v; | |
for (var x = 1; x <= colors.Count; x++) | |
{ | |
cell.Characters[x, 1].Font.Color = colors[x - 1]; | |
} | |
cell.Characters[colors.Count + 1, v.Length].Font.Color = color; | |
} | |
private static List<double> ReadColor(Microsoft.Office.Interop.Excel.Range cell) | |
{ | |
var colors = new List<double>(); | |
for (var x = 1; x <= cell.Characters.Count; x++) | |
{ | |
var c = cell.Characters[x, 1]; | |
colors.Add((double)c.Font.Color); | |
} | |
return colors; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment