简体   繁体   English

在 C# 中使用 OfficeOpenXml 在单个 Excel 单元格中设置多种样式

[英]Set Multiple styles in a single excel cell using OfficeOpenXml in C#

I cannot find a way to style a single excel cell in different styles.我找不到以不同样式设置单个 Excel 单元格的方法。 For example I need to make only some part of the string bold and leave the rest unbold in one cell.例如,我只需要将字符串的一部分加粗,其余部分不加粗在一个单元格中。 I can only access Cells not characters in OpenXml.我只能访问 OpenXml 中的单元格而不是字符。

在此处输入图像描述

Usually what I do to style the cell is,通常我对单元格的样式是,

ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets.Add("SheetName");
ws.Cells[1, 1].Style.Font.Bold = true;

I can't find a way to access characters in a cell.我找不到访问单元格中字符的方法。 I saw some other excel plugins do the same but Is there any way OpenXml can do this?我看到其他一些 excel 插件也这样做,但是 OpenXml 有什么办法可以做到这一点吗? Any suggestions will be great.任何建议都会很棒。 Thanks谢谢

The answer here works well. 这里的答案效果很好。

You have to add the cell content as separate ExcelRichText objects.您必须将单元格内容添加为单独的 ExcelRichText 对象。

Example:例子:

ExcelRichText rt1 = ws.Cells[1, 1].RichText.Add("AB");
rt1.Bold = true; // bold just the "AB"
ExcelRichText rt2 = ws.Cells[1, 1].RichText.Add("CD");

Output will be: " AB CD"输出将是:“ AB CD”

Note: You will need to reference the namespace OfficeOpenXml.Style注意:您需要引用命名空间 OfficeOpenXml.Style

This is how you can add partial styles in an excel sheet using OpenXML.这是您可以使用 OpenXML 在 Excel 工作表中添加部分样式的方法。

        //Partial Cell Styling
        uint currentRow = 2;
        Row newRow = new Row() { RowIndex = currentRow };
        //create a new inline string cell
        Cell cell = new Cell() { CellReference = "J" + currentRow.ToString() };
        cell.DataType = CellValues.InlineString;
        
        //create a run for the bold text
        Run run1 = new Run();
        run1.Append(new Text("By: "));

        //create a second run for the non-bod text
        Run run2 = new Run();
        run2.Append(new Text(Environment.NewLine + " SAHIL VIG") { Space = SpaceProcessingModeValues.Preserve });
        //create runproperties and append a "Bold" to them
        RunProperties run2Properties = new RunProperties();
        run2Properties.Append(new Bold());
        //set the first runs RunProperties to the RunProperties containing the bold
        run2.RunProperties = run2Properties;

        //create a new inline string and append both runs
        InlineString inlineString = new InlineString();
        inlineString.Append(run1);
        inlineString.Append(run2);

        //append the inlineString to the cell.
        cell.Append(inlineString);

        //append the cell to the row
        newRow.Append(cell);

        sheetData.Append(newRow);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM