最近遇到了一個問題,下載一個文檔時需要下載word可編輯的公式。找了很久終于找到了一種解決辦法。下面是以C#代碼來實現在Word中插入公式的功能。
目錄
- 一、引入dll程序集文件
- 1、通過 NuGet 引入dll(2種方法)的方法:
- 2、手動添加dll引用的方法
- 二、插入公式
- 三、如何查找并替換公式
- latex公式提取器
- 查找并進行公式替換
一、引入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();//添加一個sectionSection 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);}}}