学习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

相关推荐
微软Nav/BC专家18 小时前
Microsoft Dynamics 365 Business Central Word Add-in如何安装
word·微软erp
大C聊AI19 小时前
标书高效制作:Word 排版快捷键 + AI 工具组合工作流
word·办公技巧·效率提升·招投标·智标领航
jianwuhuang8219 小时前
豆包输出word
人工智能·ai·chatgpt·word·deepseek·ai导出鸭
chatexcel2 天前
ChatExcel AI文档上线:AI自动生成Word报告的完整工作流
人工智能·word
俊哥工具2 天前
不用安装不收费!多功能U盘修复工具,解决大部分U盘故障
学习·pdf·word·excel·音视频
草丛中的蝈蝈3 天前
word目录中的一级标题编号和标题之间距离很大,但是内容里是正常的
word
Metaphor6923 天前
使用 Python 设置 Word 文档文本的颜色
python·word
usdoc文档预览3 天前
国产化踩坑:Vue3 / React / 小程序如何免插件实现 OFD 及复杂 Office 文档同屏预览
前端·javascript·react.js·小程序·pdf·word·office文件在线预览
一头爱吃肉的牛3 天前
Word转PPT教程:三步用AI工具一键生成
人工智能·word·powerpoint
熟悉的新风景4 天前
word,wps使用技巧
word·wps