我正在开发一个 C# 程序,该程序使用 Microsoft Word 14.0 对象库创建 .doc 文件,向其中添加段落并保存。有一个带有按钮的小表单,可以执行所描述的操作(请参阅下面的代码)。这部分没有问题。
Problem:
创建的 Word 文件中的当前文本如下:
一些文本 beff = 3.0
我需要完成的是创建一个段落,其中有下标字符。(在上面的段落中,字母“eff”应该带有下标):
最终文档将包含大约 100 行,如上所示,并带有不同的下标字符。
我找到了一种用行为整个段落添加下标的方法,
paragraph1.Range.Font.Subscript = 1;
但找不到在单独的角色上实现它的方法。
我还知道 Unicode 中有下标字母和数字可以使用,但不幸的是,Unicode 没有下标格式的完整字母表,因此这也不是一个选项。
问题:
有没有办法让我实现目标并在新创建的 Word 文档的段落内的下标中插入类似“eff”的内容?
示例代码:
private void btnReport_Click(object sender, EventArgs e)
{
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oDoc = oWord.Documents.Add();
var paragraph1 = oDoc.Content.Paragraphs.Add();
paragraph1.Range.Text = "Some text beff = 3.0";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Word document|*.doc";
saveFileDialog1.Title = "Save the Word Document";
if (DialogResult.OK == saveFileDialog1.ShowDialog())
{
string docName = saveFileDialog1.FileName;
if (docName.Length > 0)
{
object oDocName = (object)docName;
oDoc.SaveAs(ref oDocName);
}
}
oWord.Quit();
}
创建一个 Word 文档并添加带有下标/上标的文本,然后解压缩 .docx 以检查其 XML 内容,您会注意到包含下标/上标的文本被放置在单独的run元素。
实现这一目标的一种方法是OpenXML SDK下载并安装SDK后,您可以使用以下代码:
using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OpenXML
{
class Program
{
static void Main(string[] args)
{
using (var doc = WordprocessingDocument.Create("C:\\Subscript.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph p = body.AppendChild(new Paragraph());
p.AppendChild(AddRun(false, "Some text b "));
p.AppendChild(AddRun(true, "eff"));
p.AppendChild(AddRun(false, "= 3.0"));
}
Console.WriteLine("Done...");
Console.ReadLine();
}
public static Run AddRun(bool isSubscript, string text)
{
Run run = new Run();
if (isSubscript)
{
var props = new RunProperties();
var fontSize = new FontSizeComplexScript() { Val = "20" };
var vAlignment = new VerticalTextAlignment() { Val = VerticalPositionValues.Subscript };
props.Append(fontSize);
props.Append(vAlignment);
run.Append(props);
}
run.Append(new Text(text));
return run;
}
}
}
EDIT:
这是一个互操作解决方案:
using WordNS = Microsoft.Office.Interop.Word;
WordNS.Document doc = _application.ActiveDocument;
WordNS.Paragraph p = doc.Paragraphs.Add();
p.Range.Text = "Some text beff = 3.0";
int start = p.Range.Text.IndexOf("eff");
int end = p.Range.Text.IndexOf("=");
WordNS.Range range = doc.Range(start, end);
range.Select();
WordNS.Selection currentSelection = _application.Selection;
currentSelection.Font.Subscript = 1;
doc.SaveAs2("C:\\SubscriptInterop.docx");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)