学习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());
    }
}

参考文献

1https://github.com/dotnet/Open-XML-SDK

2https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

3https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1

4https://blog.csdn.net/i042416/article/details/126228816

相关推荐
qq_5469372715 天前
Excel批量转PDF_Word_图片,支持自动合并报表,效率翻倍。
pdf·word·excel
(Charon)16 天前
【C++ 面试高频:内存管理、RAII 和智能指针详解】
java·开发语言·word
江畔柳前堤16 天前
github实战指南03-Pull Request 全流程实战
开发语言·人工智能·python·深度学习·github·word
2603_9541383916 天前
PDF 转 Word 工具深度评测:从参数解析到实战避坑
pdf·word
知南x17 天前
【DPDK例程学习】(4) l2fwd
学习·word
江畔柳前堤17 天前
github实战指南00-命令在哪里执行?
人工智能·线性代数·oracle·数据挖掘·github·word
江畔柳前堤17 天前
github实战指南05-Fork与开源协作
人工智能·线性代数·oracle·开源·github·word
yivifu17 天前
怎样将Word文档中脚注引用后面的空格轻松删除
word·vba
Sour18 天前
Word 文档翻译后保留格式的检查清单:标题、表格、图片、目录和批注
pdf·word·办公软件·office·文档翻译
qq_4221525719 天前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word