如何用C#结合OpenXml为Excel特定单元格设置字体颜色
用C#结合OpenXml修改Excel特定单元格字体颜色
我在应用中使用预定义Excel模板填充数据并导出,需要通过C#结合OpenXml修改特定单元格的文本字体颜色。尝试过使用Stylesheet、StyleIndex,但设置的字体颜色会应用到整个工作表,无法仅作用于特定单元格。下面是修正后的实现方案:
核心思路
要实现仅特定单元格应用字体颜色,需在Stylesheet中创建独立的自定义样式,并将该样式的索引指定给目标单元格,而非修改原有全局样式。具体步骤:
- 检查并获取工作表的Stylesheet,若不存在则创建
- 定义带指定颜色的字体
- 创建CellStyle关联该字体,并添加到Stylesheet
- 获取新样式的索引,更新单元格时设置StyleIndex为该索引
完整代码
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; private async Task<MemoryStream> ExportData(MemoryStream memory, FilterModel filterModel) { var reqModel = filterModel.reqModel; using (SpreadsheetDocument document = SpreadsheetDocument.Open(memory, true)) { IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>() .Elements<Sheet>().Where(s => s.Name == "MySheet"); string relationshipId = sheets.First().Id.Value; WorksheetPart wp = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); if (wp != null) { SheetData sheetData = wp.Worksheet.GetFirstChild<SheetData>(); if (sheetData != null) { // 获取或创建样式表 WorkbookStylesPart stylesPart = document.WorkbookPart.GetPartsOfType<WorkbookStylesPart>().FirstOrDefault(); if (stylesPart == null) { stylesPart = document.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = new Stylesheet(); } Stylesheet stylesheet = stylesPart.Stylesheet; // 创建自定义字体(红色为例,可修改Rgb值) Font customFont = new Font( new Color { Rgb = HexBinaryValue.FromString("FF0000") }, new FontSize { Val = 11 }, new FontName { Val = "Calibri" } ); // 添加字体到样式表,获取字体索引 if (stylesheet.Fonts == null) stylesheet.Fonts = new Fonts(); stylesheet.Fonts.Append(customFont); uint fontIndex = (uint)stylesheet.Fonts.Elements<Font>().Count() - 1; // 创建CellStyle,关联自定义字体 CellFormat cellFormat = new CellFormat { FontId = fontIndex, FillId = 0, // 使用默认填充 BorderId = 0, // 使用默认边框 FormatId = 0, // 使用默认数字格式 ApplyFont = true // 仅应用字体样式 }; // 添加CellFormat到样式表,获取样式索引 if (stylesheet.CellFormats == null) stylesheet.CellFormats = new CellFormats(); stylesheet.CellFormats.Append(cellFormat); uint styleIndex = (uint)stylesheet.CellFormats.Elements<CellFormat>().Count() - 1; // 保存样式表 stylesheet.Save(); UInt32Value? RowIndex = 2; foreach (var des in filterModel.designations) { UpdateCell(sheetData, "C", RowIndex, des.Name, false, styleIndex); RowIndex++; } wp.Worksheet.Save(); document.WorkbookPart.Workbook.Save(); } } } return memory; } private void UpdateCell(SheetData sd, string colName, UInt32 rowIndex, string value, bool isNumber = false, uint? styleIndex = null) { string cellReference = colName + rowIndex; Row r = sd.Elements<Row>().FirstOrDefault(ri => ri.RowIndex == rowIndex); if (r == null) return; Cell c = r.Elements<Cell>().FirstOrDefault(cr => cr.CellReference?.Value == cellReference); if (c != null) { c.DataType = isNumber ? CellValues.Number : CellValues.String; if (c.DataType == CellValues.SharedString) c.DataType = CellValues.String; c.CellValue = new CellValue(value); // 给目标单元格指定自定义样式索引 if (styleIndex.HasValue) c.StyleIndex = styleIndex.Value; } }
代码说明
- 样式表初始化:先检查WorkbookStylesPart是否存在,不存在则创建;同时确保Fonts和CellFormats集合不为空,避免空引用异常
- 自定义字体配置:创建包含指定RGB颜色的Font对象,示例中用红色(FF0000),可根据需求修改Rgb属性值
- 单元格格式关联:创建CellFormat绑定自定义字体,设置
ApplyFont=true确保仅覆盖字体样式,保留单元格原有填充、边框等格式 - 单元格更新:扩展UpdateCell方法,增加styleIndex参数,仅给目标单元格指定自定义样式索引,实现局部字体颜色修改
内容的提问来源于stack exchange,提问作者user24241471
相关产品推荐
相关产品推荐

