gpt4 book ai didi

c# - 打开 XML SDK : Format part of an Excel-cell

转载 作者:太空狗 更新时间:2023-10-29 20:21:45 25 4
gpt4 key购买 nike

将 Open XML for Excel 与 DocumentFormat.OpenXml.Spreadsheet 结合使用,如何仅将部分文本设置为粗体?

var cell = new Cell {
//DataType = CellValues.InlineString,
CellReference = "A" + 1
};

// TODO: Set "bold text" to bold style
//var inlineString = new InlineString();
//inlineString.AppendChild(new Text { Text = "Normal text... bold text..." });
//cell.AppendChild(inlineString);

注释掉现在使用但应该或可能应该更改的代码。

最佳答案

要仅将部分文本设置为粗体,您需要通过将文本插入 SharedStringTable 并将单元格的数据类型设置为 SharedString 而不是 内联字符串。这将使 CellValue 成为此表的引用,如 0、1、2 等,并允许更多控制然后执行内联字符串。

下面是一些示例代码,说明如何将短语“普通文本...粗体文本...”的第二部分设为粗体:

       // Creates an SharedStringItem instance and adds its children.
public SharedStringItem GenerateSharedStringItem()
{
SharedStringItem sharedStringItem1 = new SharedStringItem();

Run run1 = new Run();
Text text1 = new Text(){ Space = SpaceProcessingModeValues.Preserve };
text1.Text = "Normal text… ";

run1.Append(text1);

Run run2 = new Run();

RunProperties runProperties1 = new RunProperties();
Bold bold1 = new Bold();
FontSize fontSize1 = new FontSize(){ Val = 11D };
Color color1 = new Color(){ Theme = (UInt32Value)1U };
RunFont runFont1 = new RunFont(){ Val = "Calibri" };
FontFamily fontFamily1 = new FontFamily(){ Val = 2 };
FontScheme fontScheme1 = new FontScheme(){ Val = FontSchemeValues.Minor };

runProperties1.Append(bold1);
runProperties1.Append(fontSize1);
runProperties1.Append(color1);
runProperties1.Append(runFont1);
runProperties1.Append(fontFamily1);
runProperties1.Append(fontScheme1);
Text text2 = new Text();
text2.Text = "bold text…";

run2.Append(runProperties1);
run2.Append(text2);

sharedStringItem1.Append(run1);
sharedStringItem1.Append(run2);
return sharedStringItem1;
}

要使用此方法,您首先要找到 SharedStringTable 的实例,然后将新的 ShareStringItem 插入其中:

            using (MemoryStream stream = new MemoryStream())
{
// create in-memory copy of the Excel template file
byte[] byteArray = File.ReadAllBytes(TEMPLATE_FILE_NAME);
stream.Write(byteArray, 0, (int)byteArray.Length);

using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, true))
{
// Set private variable template component references (for reuse between methods)
mExcelWorkbookPart = document.WorkbookPart;
mSharedStringTablePart = mExcelWorkbookPart.SharedStringTablePart;

mSharedStringTablePart.SharedStringTable.AppendChild(GenerateSharedStringItem());
}

return stream.ToArray();
}

关于c# - 打开 XML SDK : Format part of an Excel-cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com