123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using DocumentFormat.OpenXml;
- using DocumentFormat.OpenXml.Packaging;
- using DocumentFormat.OpenXml.Wordprocessing;
- using Spire.Doc;
- using System.IO;
- using Break = DocumentFormat.OpenXml.Wordprocessing.Break;
- using Document = Spire.Doc.Document;
- namespace UniformMaterialManagementSystem.Utils
- {
- public static class WordUtil
- {
- /// <summary>
- /// 按时间生成14位流水号
- /// </summary>
- /// <returns></returns>
- public static string GenerateFileSerialNumber()
- {
- DateTime now = DateTime.Now;
- string datePart = now.ToString("yyyyMMddHHmmss");
- long ticks = now.Ticks - new DateTime(2000, 1, 1, 0, 0, 0).Ticks;
- string ticksPart = ticks.ToString().Substring(0, 14 - datePart.Length);
- return datePart + ticksPart;
- }
- /// <summary>
- /// 根据模板生成新的word文档,并替换文档内容
- /// </summary>
- public static void GenerateWordByTemplate(string templateFilePath,string targetFilePath, Dictionary<string, string> replaceContentDic)
- {
- File.Copy(templateFilePath, targetFilePath, true);
- using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(targetFilePath, true))
- {
- MainDocumentPart? mainDocPart = wordDocument.MainDocumentPart;
- //替换word内容
- UpdateWordDocumentText(replaceContentDic, mainDocPart);
- }
- }
- /// <summary>
- /// 将word文档保存为pdf文档
- /// </summary>
- public static void SaveWordToPdf(string inputFilePath, string outputFilePath)
- {
- Document document = new Document();
- document.LoadFromFile(inputFilePath);
- document.SaveToFile(outputFilePath, FileFormat.PDF);
- }
- /// <summary>
- /// 根据tagId替换word文档中的内容
- /// </summary>
- private static void UpdateWordDocumentText(Dictionary<string, string> tagValueDict, MainDocumentPart? mainDocPart)
- {
- foreach (var pair in tagValueDict)
- {
- var tagId = pair.Key;
- var value = pair.Value;
- foreach (var sdtElement in mainDocPart.Document.Body.Descendants<SdtElement>())
- {
- if (sdtElement.SdtProperties.GetFirstChild<Tag>().Val == tagId)
- {
- OpenXmlElement? parantElement = sdtElement.Descendants<Paragraph>().SingleOrDefault();
- if (null == parantElement)
- {
- SdtContentRun? cr = sdtElement.Descendants<SdtContentRun>().SingleOrDefault();
- parantElement = cr;
- }
- if (null != parantElement)
- {
- Run? run = parantElement.Descendants<Run>().SingleOrDefault();
- if (null != run)
- {
- Text? t = run.Descendants<Text>().SingleOrDefault();
- if (null != t)
- {
- if (value.Contains(Environment.NewLine))
- {
- var values = value.Split(Environment.NewLine);
- foreach (var line in values)
- {
- run.Append(new Text(line));
- run.Append(new Break());
- }
- }
- else
- {
- run.AppendChild(new Text(value));
- }
-
- run.RemoveChild(t);
- }
- }
- break;
- }
- }
- }
- }
- }
- }
- }
|