最近遇到了一个问题,下载一个文档时需要下载word可编辑的公式。找了很久终于找到了一种解决办法。下面是以C#代码来实现在Word中插入公式的功能。
一、引入dll程序集文件
1、通过 NuGet 引入dll(2种方法)的方法:
可以在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“管理NuGet包”,然后搜索“Free Spire.Doc”,点击“安装”。等待程序安装完成。
将以下内容复制到PM控制台安装:
Install-Package FreeSpire.Doc -Version 10.2
2、手动添加dll引用的方法
可通过手动下载包到本地,然后解压,找到BIN文件夹下的Spire.Doc.dll。然后在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“添加引用”,将本地路径BIN文件夹下的dll文件添加引用至程序。
二、插入公式
在编辑公式时,通过 OfficeMath.FromLatexMathCode()
方法和 OfficeMath.FromMathMLCode()
方法来添加LaTeX公式及MathML公式。开发者可根据程序设计需要选择其中对应的方法来编辑公式即可。
下面是本次程序代码实现公式添加的主要代码步骤:
- 创建
Document
类的对象,并调用Document.AddSection()
方法添加节到Word文档。 - 通过
Section.AddParagraph()
方法添加段落。 - 初始化 OfficeMath类的实例。通过
OfficeMath.FromLatexMathCode(string latexMathCode)
方法编辑LeTeX公式;通过OfficeMath.FromMathMLCode(string mathMLCode)
方法编辑MathML公式。 - 通过
DocumentObjectCollection.Add(Spire.Doc.Interface.IDocumentObject entity)
方法添加公式到段落。 - 最后,通过
Document.SaveToFile(string fileName, FileFormat fileFormat)
方法保存文档。
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.OMath;
namespace InsertFormula
{
class Program
{
static void Main(string[] args)
{
//新建word实例
Document doc = new Document();
//添加一个section
Section section = doc.AddSection();
//添加一个段落
Paragraph paragraph = section.AddParagraph();
//在第一段添加Latex公式
OfficeMath officeMath = new OfficeMath(doc);
officeMath.FromLatexMathCode("x^{2}+\\sqrt{x^{2}+1}=2");
paragraph.Items.Add(officeMath);
//添加MathML公式到第四段
Paragraph paragraph1 = section.AddParagraph();
OfficeMath officeMath1 = new OfficeMath(doc);
officeMath1.FromMathMLCode("<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:msqrt><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:msqrt><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:math>");
paragraph1.Items.Add(officeMath1);
//这里可以进行自己的操作添加数据。。。
//保存文档
doc.SaveToFile("InsertFormulas.docx", FileFormat.Docx);
}
}
}
结果:
三、如何查找并替换公式
有时候我们并不是直接插入公式,公式存在于文本值中,这个时候我们就需要在文本中替换公式部分。
结果如下:
latex公式提取器
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace TEST;
/// <summary>
/// Latex公式提取器
/// </summary>
public class LatexFormulaExtractor
{
// 正则表达式模式组合:匹配所有可能的 LaTeX 公式形式
private static readonly Regex LaTeXPattern = new Regex(
// 匹配 LaTeX 环境(如 \begin{equation}...\end{equation})
@"\\begin\{([a-zA-Z]+\*?)\}.*?\\end\{\1\}" + "|" +
// 匹配 $$...$$ 或 \[...\]
@"\${2}(.*?)\${2}|\\\[(.*?)\\\]" + "|" +
// 匹配 $...$(需排除转义的 \$)
@"(?<!\\)\$((?:[^$\\]|\\.)*?)(?<!\\)\$",
RegexOptions.Singleline | RegexOptions.IgnoreCase
);
/// <summary>
/// 从文本中提取所有 LaTeX 公式
/// </summary>
public static List<string> ExtractLatexFormulas(string input)
{
var formulas = new List<string>();
if (string.IsNullOrWhiteSpace(input)) return formulas;
// 遍历所有匹配项
foreach (Match match in LaTeXPattern.Matches(input))
{
if (match.Success)
{
// 提取匹配的公式内容(处理不同捕获组)
string formula = match.Groups[0].Value;
formulas.Add(formula);
}
}
return formulas;
}
}
查找并进行公式替换
var formulas = LatexFormulaExtractor.ExtractLatexFormulas(htmlContent);
foreach (var formula in formulas)
{
// 添加Office Math公式
OfficeMath math = new OfficeMath(doc);
// 确保OfficeMath对象正确初始化
if (math != null)
{
math.FromLatexMathCode(formula); // 使用LaTeX语法插入公式
}
//查找文档中的指定文本内容
TextSelection[] selections = doc.FindAllString(@formula, true, true);
int tindex = 0;
TextRange range = null;
//遍历文档,移除文本内容,插入公式
if (selections != null)
{
foreach (TextSelection selection in selections)
{
range = selection.GetAsOneRange();
tindex = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(tindex, math);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}