C#使用openxml-sdk生成word文档

从nuget中安装openxml

 

 测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using (WordprocessingDocument doc = WordprocessingDocument.Create("test.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
 
 
    MainDocumentPart mainPart = doc.AddMainDocumentPart();
    //文档内容html
    new Document(new Body()).Save(mainPart);
    string altChunkId = "id";
    string table = "<table style=\"border-collapse: collapse; \">";
    for (int i = 0; i < 3; i++)
    {
        table += "<tr>";
        for (int j = 0; j < 5; j++)
        {
            table += "<td style=\"border: 1px solid red; width: 200px\">66666</td>";
        }
        table += "</tr>";
    }
    table += "</table>";
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes($"<html><head><meta charset=\"UTF-8\"></head><body><h1 style=\"color:red\" >我是标题111</h1><span>我是表格666666666666666666</span>{table}</body></html>"));
    AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
    formatImportPart.FeedData(ms);
    AltChunk altChunk = new AltChunk();
    altChunk.Id = altChunkId;
    mainPart.Document.Body.Append(altChunk);
 
    //页眉页脚和样式
    RunProperties Properties = new RunProperties() {Underline=new Underline() { Val= UnderlineValues .Single} };
    var run = new Run(new Text() { Text = "我是页眉                         哈哈哈哈哈 0.123456" });
    run.PrependChild(Properties);
 
 
    Header header = new Header(new Paragraph(run));
    Footer footer = new Footer(new Paragraph(new Run(new Text() { Text = "我是页脚" })));
 
 
    mainPart.AddNewPart<HeaderPart>("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", "r01").Header = header;
    mainPart.AddNewPart<FooterPart>("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", "r02").Footer = footer;
    SectionProperties sp = new SectionProperties(
        new HeaderReference() { Id = "r01", Type = HeaderFooterValues.Default },
        new FooterReference() { Id = "r02", Type = HeaderFooterValues.Default }
        );
 
    mainPart.Document.Body.AppendChild<SectionProperties>(sp);
 
    //页边距
    SectionProperties sectionProps = new SectionProperties();
    PageMargin pageMargin = new PageMargin() { Top = 1440, Right = 1440, Bottom = 1440, Left = 1440, Header = 1080, Footer = 720, Gutter = 0 };
    sectionProps.Append(pageMargin);
    mainPart.Document.Body.Append(sectionProps);
 
    mainPart.Document.Save();
}

  效果

 

posted @   奇迹之耀  阅读(497)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-02-10 mysql创建索引,多字段唯一约束
点击右上角即可分享
微信分享提示