学习C#调用OpenXml操作word文档的基本用法(30:学习日期相关类)

文本运行类Run的子类型DayShort、DayLong、MonthShort、MonthLong、YearShort及YearLong用于向文本中插入年月日等信息,命名空间为DocumentFormat.OpenXml. Wordprocessing,对应document.xml文件内的元素如下图所示:

  上述六种日期类型继承自EmptyType,不包含任何用于控制格式的属性,其显示格式(如日期的长短格式)完全固定。六种日期类型的说明如下表所示:

序号 名称 说明
1 DayShort 插入短日期(两位数日期),如12,xml文件中对应的标签为<w:dayShort />
2 DayLong 插入长日期(星期几的完整名称),如Tuesday,xml文件中对应的标签为<w:dayLong />
3 MonthShort 插入短月份(数字),如4,xml文件中对应的标签为<w:monthShort />
4 MonthLong 插入长月份(月份完整名称)如April,xml文件中对应的标签为<w:monthLong />
5 YearShort 插入短年份(两位数年份),如26,xml文件中对应的标签为<w:yearShort />
6 YearLong 插入长年份(四位数年份),如2026 ,xml文件中对应的标签为<w:yearLong />

最后是使用示例及运行效果,如下所示:

csharp 复制代码
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(sfd.FileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());
    
    Paragraph paragraph = body.AppendChild(new Paragraph());
    Run run = paragraph.AppendChild(new Run());

    for (int i = 0; i < txtContent.Lines.Length; i++) 
    {
        Text text = new Text();
        text.Space = SpaceProcessingModeValues.Preserve;
        text.Text = txtContent.Lines[i];
        run.AppendChild(text);

        run.Append(new Break());
    }

    run.Append(new Text("----------------------------------日期:"));

    if(rbShortDate.Checked)
    {
        run.Append(new YearShort());
        run.Append(new Text("-"));
        run.Append(new MonthShort());
        run.Append(new Text("-"));
        run.Append(new DayShort());
    }

    if (rbLongDate.Checked)
    {
        run.Append(new YearLong());
        run.Append(new Text("-"));
        run.Append(new MonthLong());
        run.Append(new Text("-"));
        run.Append(new DayLong());
    }
}

参考文献

1\]https://github.com/dotnet/Open-XML-SDK \[2\]https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk \[3\]https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1 \[4\]https://blog.csdn.net/i042416/article/details/126228816

相关推荐
gc_22994 小时前
学习C#调用OpenXml操作word文档的基本用法(28:学习文本类)
word·文本·text·openxml
2501_907136825 小时前
HandyWrite Pro - word/excel转手写工具
word·软件需求
Eiceblue5 小时前
C# 如何实现 Word 转 Excel ?分享两种实用方法
c#·word·excel
天才少女爱迪生5 小时前
word格式规范检测+自动修改【python】
python·c#·word
gc_22996 小时前
学习C#调用OpenXml操作word文档的基本用法(29:学习中断类)
word·中断·openxml·break
梅孔立7 小时前
Aspose.Words Java 表格动态删列、合并列、表头重建、全局字体统一解决方案
java·开发语言·word·aspose·在线编辑
爱叨叨的小嘟1 天前
Latex公式 转 word可编辑公式
word·typora·latex
gc_22991 天前
学习C#调用OpenXml操作word文档的基本用法(27:学习文本运行类-续)
word·openxml·run·runproperties
ONLYOFFICE1 天前
如何将 Word 集成到 Web 应用程序? 5 种方法详解与对比
前端·word·onlyoffice