Excel中的文本部分颜色> 255个字符

我已经为第三方sw编写了一个插件,它可以将修改后的文本提取到Excel工作表中,然后在Excel中着色更改的部分。 只要每个文本段(=单元格内容)不超过255个字符,这都是有效的。 唉,这可以,偶尔也会发生。

为了在Excel中识别已更改的部分,我用<del>和res。 用于删除和添加文本的<add>标签。 然后我为这些部分着色(并删除周围的标签),如下所示:

 while (((string)cell1.Text).Contains("<del>")) { try { var pos = ((string) cell1.Text).IndexOf("<del>") + 1; var pos2 = ((string) cell1.Text).IndexOf("</del>") + 1; var txt = cell1.Characters[pos, (pos2-pos) + 9].Text; txt = txt.Replace("<del>", "").Replace("</del>", ""); cell1.Characters[pos, (pos2-pos) + 9].Text = txt; cell1.Characters[pos, txt.Length-3].Font.Color = -16776961; } catch { break; } } 

我正在使用Interop,因为我觉得使用起来要容易得多,而且因为找不到像OpenXML这样的例子。 但是我意识到Excel在单元格文本方面有其局限性,所以我愿意提供build议。

有没有办法使用Interop在包含> 255个字符的单元格中对单个单词进行着色?

如果一切都失败了,我可能不得不用表格创build一个Word文档,在那里进行格式化,然后复制/粘贴到Excel(yukk)。 请帮我避免这个丑陋。

PS:是的,修订总结需要基于Excel。

好的,我现在用OpenXML解决了它。 如果一个单元格包含要着色的文本,则创build一个文本到该位置的文本,第二个包含受影响文本的彩色运行,以及第三个包含其余文本的返回到默认运行。

 var xlsx = SpreadsheetDocument.Open(xlsPath, true); var contents = xlsx.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First(); foreach (SharedStringItem si in contents.SharedStringTable.Elements<SharedStringItem>()) { if (si.Text != null) { XlHelper.ColorCellText(si, "del", new DocumentFormat.OpenXml.Spreadsheet.Color { Rgb = "FFFF0000" }); XlHelper.ColorCellText(si, "add", new DocumentFormat.OpenXml.Spreadsheet.Color { Rgb = "0000BF00" }); } } 

和我的XlHelper.ColorCellText方法:

 public static void ColorCellText(SharedStringItem si, string TagName, DocumentFormat.OpenXml.Spreadsheet.Color col) { var newText = si.InnerText; var startTag = string.Format("<{0}>", TagName); var endTag = string.Format("</{0}>", TagName); if (newText.Contains(startTag)) { si.Text.Remove(); var lastpos = 0; while (newText.Contains(startTag)) { try { var pos1 = newText.IndexOf(startTag); var pos2 = newText.IndexOf(endTag); var txtLen = pos2 - pos1 - 5; var it = string.Concat(newText.Substring(0, pos1), newText.Substring(pos1 + 5, txtLen), newText.Substring(pos2 + 6)); var run = new Run(); var txt = new Text { Text = it.Substring(0, pos1), Space = SpaceProcessingModeValues.Preserve }; run.Append(txt); si.Append(run); run = new Run(); txt = new Text { Text = it.Substring(pos1, txtLen), Space = SpaceProcessingModeValues.Preserve }; var rp = new RunProperties(); rp.Append(col.CloneNode(true)); run.RunProperties = rp; run.Append(txt.CloneNode(true)); si.Append(run.CloneNode(true)); newText = newText.Substring(pos2 + 6); } catch(Exception ex) { using (var sw = new StreamWriter(logFile, true)) { sw.WriteLine("Error: {0}\r\n{1}", ex.Message, newText); } break; } } if (newText.Length>=0) { var lastrun = new Run(); var lasttxt = new Text { Text = newText, Space = SpaceProcessingModeValues.Preserve }; lastrun.Append(lasttxt); si.Append(lastrun); } } } 

Space = SpaceProcessingModeValues.Preserve部分在这里是至关重要的,否则它会将所有三个部分粘合在一起,并消除之间的空间。

我想我会研究这个EPPlus,因为它的“In-cell Richtext”function听起来很有前途。