OpenXMl创建word并添加标题居中显示

1、创建Word

public class OpenXmlWordUtility
{
		/// <summary>
        /// 文件全路径
        /// </summary>
        public string FilePath { get; private set; }

        /// <summary>
        /// 处理文档
        /// </summary>
        public WordprocessingDocument ProcessingDocument { get; private set; }

        /// <summary>
        /// 文档
        /// </summary>
        public Document Document
        {
            get
            {
                return this.ProcessingDocument.MainDocumentPart.Document;
            }
        }
        /// <summary>
        /// 打开文档
        /// </summary>
        public void OpenDocument()
        {
            this.ProcessingDocument = WordprocessingDocument.Open(this.FilePath, true);

            this.TitleParagraphs = this.GetTitleParagraphs();
        }

        /// <summary>
        /// 创建Word文档
        /// </summary>
        public void CreateDocument()
        {
            this.ProcessingDocument = WordprocessingDocument.Create(this.FilePath, WordprocessingDocumentType.Document);

            MainDocumentPart mainDocumentPart = this.ProcessingDocument.AddMainDocumentPart();
            mainDocumentPart.Document = new Document(new Body());
            Body body = mainDocumentPart.Document.Body;

            SectionProperties sectionProperties = new SectionProperties();
            PageSize pageSize = new PageSize();
            PageMargin pageMargin = new PageMargin();
            DocumentFormat.OpenXml.Wordprocessing.Columns columns = new DocumentFormat.OpenXml.Wordprocessing.Columns() { Space = "220" }; //720  
            DocGrid docGrid = new DocGrid() { LinePitch = 100 }; //360  

            sectionProperties.Append(pageSize, pageMargin, columns, docGrid);
            body.Append(sectionProperties);

            mainDocumentPart.Document.Save();
        }

        /// <summary>
        /// 保存文档
        /// </summary>
        public void SaveDocument()
        {
            this.ProcessingDocument.MainDocumentPart.Document.Save();
        }

        /// <summary>
        /// 关闭文档
        /// </summary>
        public void CloseDocument()
        {
            if (this.ProcessingDocument != null)
            {
                this.ProcessingDocument.Close();
                this.ProcessingDocument.Dispose();
            }
        }
        /// <summary>
        /// 清除指定标题下的所有内容
        /// </summary>
        public void ClearTitleContent(WordTitle title)
        {
            var index = this.WordTitles.IndexOf(title);

            //title.Paragraph.NextSibling().RemoveAllChildren();

            //return;

            OpenXmlElement startElement = title.Paragraph.NextSibling();
            OpenXmlElement stopElement = null;

            if (index != this.WordTitles.Count - 1)
            {
                var tempLt = this.WordTitles.Skip(index + 1);

                var tagTitle = tempLt.FirstOrDefault(p => p.Level == title.Level);

                if (tagTitle != null)
                {
                    stopElement = tagTitle.Paragraph;
                    OpenXmlElement tempElement = startElement;

                    List<OpenXmlElement> openxmleList = new List<OpenXmlElement>();

                    while (tempElement != stopElement)
                    {
                        openxmleList.Add(tempElement);
                        tempElement = tempElement.NextSibling();
                    }

                    foreach (var openXmlElement in openxmleList)
                    {
                        openXmlElement.Remove();
                    }
                }
                else // 等于null 通常是最后一个章节
                {
                    stopElement = null;
                    OpenXmlElement tempElement = startElement;

                    List<OpenXmlElement> openxmleList = new List<OpenXmlElement>();

                    while (tempElement != stopElement)
                    {
                        openxmleList.Add(tempElement);
                        tempElement = tempElement.NextSibling();
                    }

                    foreach (var openXmlElement in openxmleList)
                    {
                        openXmlElement.Remove();
                    }
                }
            }
        }

        /// <summary>
        /// 创建纵向页分节符
        /// </summary>
        /// <returns></returns>
        public Paragraph CreatePortraitSectionBreakParagraph()
        {
            Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00052B73", RsidRunAdditionDefault = "00052B73" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();

            SectionProperties sectionProperties1 = new SectionProperties() { RsidR = "00052B73" };
            //  PageSize pageSize1 = new PageSize() { Width = (UInt32Value)16838U, Height = (UInt32Value)11906U, Orient = PageOrientationValues.Landscape };
            PageSize pageSize1 = new PageSize();
            //PageMargin pageMargin1 = new PageMargin() { Top = 1440, Right = (UInt32Value)1800U, Bottom = 1440, Left = (UInt32Value)1800U, Header = (UInt32Value)851U, Footer = (UInt32Value)992U, Gutter = (UInt32Value)0U };
            DocumentFormat.OpenXml.Wordprocessing.Columns columns1 = new DocumentFormat.OpenXml.Wordprocessing.Columns() { Space = "425" };
            DocGrid docGrid1 = new DocGrid() { Type = DocGridValues.Lines, LinePitch = 312 };

            sectionProperties1.Append(pageSize1);
            //  sectionProperties1.Append(pageMargin1);
            sectionProperties1.Append(columns1);
            sectionProperties1.Append(docGrid1);

            paragraphProperties1.Append(sectionProperties1);

            paragraph1.Append(paragraphProperties1);
            return paragraph1;
        }
        /// <summary>
        /// 获取新段落
        /// </summary>
        /// <param name="text">段落文本</param>
        /// <returns>段落</returns>
        public Paragraph CreateParagraph(string text)
        {
            Paragraph paragraph = new Paragraph();
            Run run = new Run();

            run.Append(new Text(text));
            paragraph.Append(run);

            return paragraph;
        }
}  

2、新增标题并居中显示

	OpenXmlWordUtility wordUtility = new OpenXmlWordUtility();
	DocumentFormat.OpenXml.Wordprocessing.Paragraph par = this.WordUtility.CreateParagraph("1");	//新建标题1
	par.PrependChild(new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties());
	
	DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties pPr2 = par.ParagraphProperties;
	
	// 设置StyleId  
	if (pPr2.ParagraphStyleId == null)
	    pPr2.ParagraphStyleId = new DocumentFormat.OpenXml.Wordprocessing.ParagraphStyleId();
	pPr2.ParagraphStyleId.Val = "1";
	if (pPr2.Justification== null)
	    pPr2.Justification= new DocumentFormat.OpenXml.Wordprocessing.Justification(){ Vall = DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center};
	this.WordUtility.Document.Body.Append(par);
	StyleDefinitionsPart styleDefinitionsPart1 = this.WordUtility.Document.MainDocumentPart.AddNewPart<StyleDefinitionsPart>("rId1");
	GeneratedCode.GeneratedClass.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);
	this.WordUtility.SaveDocument();
	this.WordUtility.CloseDocument();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C# Open XML添加图片并居中的示例代码: ```csharp using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using A = DocumentFormat.OpenXml.Drawing; using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; using PIC = DocumentFormat.OpenXml.Drawing.Pictures; public void AddCenteredImage(string imagePath, string documentPath) { using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true)) { MainDocumentPart mainPart = document.MainDocumentPart; // 创建一个段落 Paragraph paragraph = new Paragraph(); // 创建一个段落属性 ParagraphProperties paragraphProperties = new ParagraphProperties(); Justification justification = new Justification() { Val = JustificationValues.Center }; // 将段落属性添加到段落 paragraphProperties.Append(justification); paragraph.Append(paragraphProperties); // 创建一个Run Run run = new Run(); // 创建一个Drawing Drawing drawing = new Drawing(); // 创建一个Inline Inline inline = new Inline(); // 创建一个Graphic Graphic graphic = new Graphic(); // 创建一个GraphicData GraphicData graphicData = new GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; // 创建一个Picture PIC.Picture picture = new PIC.Picture(); // 创建一个BlipFill PIC.BlipFill blipFill = new PIC.BlipFill(); // 创建一个Blip A.Blip blip = new A.Blip() { Embed = mainPart.GetIdOfPart(mainPart.AddImagePart(ImagePartType.Jpeg)) }; // 创建一个Stretch A.Stretch stretch = new A.Stretch(); A.FillRectangle fillRectangle = new A.FillRectangle(); // 将Blip添加到BlipFill blipFill.Append(blip); blipFill.Append(stretch); // 将BlipFill添加到Picture picture.Append(blipFill); picture.Append(fillRectangle); // 创建一个ShapeProperties PIC.ShapeProperties shapeProperties = new PIC.ShapeProperties(); // 创建一个Transform2D A.Transform2D transform2D = new A.Transform2D(); // 创建一个Offset A.Offset offset = new A.Offset() { X = 0, Y = 0 }; // 创建一个Extent A.Extents extents = new A.Extents() { Cx = 914400, Cy = 914400 }; // 将Offset和Extent添加到Transform2D transform2D.Append(offset); transform2D.Append(extents); // 将Transform2D添加到ShapeProperties shapeProperties.Append(transform2D); // 将ShapeProperties添加到Picture picture.Append(shapeProperties); // 将Picture添加到GraphicData graphicData.Append(picture); // 将GraphicData添加到Graphic graphic.Append(graphicData); // 将Graphic添加到Inline inline.Append(graphic); // 将Inline添加到Drawing drawing.Append(inline); // 将Drawing添加到Run run.Append(drawing); // 将Run添加到段落 paragraph.Append(run); // 将段落添加到文档主体 mainPart.Document.Body.Append(paragraph); // 保存文档 mainPart.Document.Save(); } } ``` 请注意,您需要将`imagePath`替换为您要添加的图片的路径,将`documentPath`替换为您要保存的Word文档的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值