ASPOSE.Word 開發資料整理


1.總體說明:操作主要涉及兩個對象Document及DocumentBuilder

Document主要用來獲取文檔中的節點,DocumentBuilder主要用於實現文檔內容的寫入

            doc_Operate = new Document(blankTemplatePth);
                    doc_template = new Document(ToCopytemplatePth);
                    builder_template = new DocumentBuilder(doc_template);
                    builder_operate = new DocumentBuilder(doc_Operate);

2.內容寫入,樣式設置

            builder_operate.ParagraphFormat.Style = doc_Operate.Styles["標題"];
                    builder_operate.Writeln("XXX報告");
                    builder_operate.ParagraphFormat.Style = doc_Operate.Styles["正文"];
                    builder_operate.Writeln("(征求意見稿)");

3.關於分節,分節之后,需要將當前插入光標移動至新插入的Section中,否則容易出錯

            builder_operate.InsertBreak(BreakType.SectionBreakNewPage);
                    Section lstSection2 = doc_Operate.LastSection;
                    int idx2 = doc_Operate.Sections.IndexOf(lstSection2);
                    builder_operate.MoveToSection(idx2);
                    builder_operate.MoveToDocumentEnd();

4.復制模板文檔中的表格,插入到當前文檔中

        //獲取Table對象
        Table tbN=doc.ImportNode(tb, true, ImportFormatMode.KeepSourceFormatting) as Table; doc.LastSection.Body.AppendChild(tbN); Paragraph p = new Paragraph(doc); tbN.ParentNode.AppendChild(p); //添加paragraph,以打斷表格

5.當前表格插入新行

Row rN = table_N.Rows[1].Clone(true) as Row;
table_N.InsertAfter(rN, table_N.LastRow);

6.單元格插入圖片

builder_operate.MoveToCell(tableindex, 0, 0, 0);
Aspose.Words.Drawing.Shape spa = builder_operate.InsertImage(jietuA);

此處插入圖片時,容易出現異常,提示tableindex超出索引,TableIndex是通過indexOf對象獲取到的.

查閱大量資料發現,如果一個word文檔中出現了多個Section,需要采用本篇第3小節的內容,移動當前的光標

7.設置單元格內容

public static void setCellText(this Cell cell, string txt)
        {
            Run run;
            if (cell.FirstParagraph.Runs.Count == 0)
            {
                run = new Run(cell.Document);
            }
            else
            {
                run = (Run)cell.FirstParagraph.Runs[0].Clone(true);                
            }
            run.Text = txt;
            for (int i = 1; i < cell.Paragraphs.Count; i++)
            {
                Node np=cell.GetChild(NodeType.Paragraph, i, false);
                cell.RemoveChild(np);
            }
            
            cell.FirstParagraph.RemoveAllChildren();
            cell.EnsureMinimum();
            if(cell.Paragraphs.Count!=0)
                cell.Paragraphs[0].AppendChild(run);
        }

8.合並單元格

public static void HorizontallyMergeCells(Cell c1, Cell c2,bool SaveAllVal=false)
        {
            c1.CellFormat.HorizontalMerge = CellMerge.First;

            //Move all content from next cell to previous
            if (SaveAllVal)
            {
                foreach (Node child in c2.ChildNodes)
                    c1.AppendChild(child);
            }

            c2.CellFormat.HorizontalMerge = CellMerge.Previous;
        }

        public static void VerticallyMergeCells(Cell c1, Cell c2,bool SaveAllVal)
        {
            c1.CellFormat.VerticalMerge = CellMerge.First;

            //Move all content from bottom cell to top
            if (SaveAllVal)
            {
                foreach (Node child in c2.ChildNodes)
                    c1.AppendChild(child);
            }

            c2.CellFormat.VerticalMerge = CellMerge.Previous;
        }

        public static void MergeCell(this Table tb, int startrowid, int endrowid, int startColId, int endColId)
        {
            for (int i = startrowid; i <= endrowid; i++)
            {
                for (int j = startColId+1; j <= endColId; j++)
                {
                    //每行進行橫向合並
                    HorizontallyMergeCells(tb.Rows[i].Cells[startColId], tb.Rows[i].Cells[j]);
                }
            }

            //首行進行縱向合並
            for (int i = startrowid+1; i <= endrowid; i++)
            {
                VerticallyMergeCells(tb.Rows[startrowid].Cells[startColId], tb.Rows[i].Cells[startColId], false);
            }
        }

9.插入另一個Word文檔

Document docShuoMing = new Document(summaryTemplatePth);
            //docShuoMing.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
            //docShuoMing.FirstSection.PageSetup.RestartPageNumbering = true;
            doc_Operate.LastSection.AppendContent(docShuoMing.FirstSection);
            //doc_Operate.AppendDocument(docShuoMing, ImportFormatMode.KeepSourceFormatting);
            builder_operate.MoveToDocumentEnd();

10.插入頁碼

public static void InsertHeaderFooter(Section sect, HeaderFooterType headerType)
        {
            HeaderFooter header = sect.HeadersFooters[headerType];
            
            if (header == null)
            {
                header = new HeaderFooter(sect.Document, headerType);
                sect.HeadersFooters.Add(header);
            }
        }

        public static void CancelHeaderFotter(Section sect)
        {
            for (int i = sect.HeadersFooters.Count-1; i >=0; i--)
            {
                sect.HeadersFooters.RemoveAt(i);
            }
        }

 

/// <summary>
        /// 插入頁碼
        /// </summary>
        /// <param name="builder_operate"></param>
        /// <param name="sec"></param>
        /// <param name="startNumber"></param>
        public static void InsertYeMa(DocumentBuilder builder_operate,Section sec,NumberStyle ns=NumberStyle.Arabic,int startNumber=1)
        {
            //添加頁碼
            ASPWHelper.InsertHeaderFooter(sec, HeaderFooterType.HeaderPrimary);
            builder_operate.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
            //設置開始頁碼
            builder_operate.PageSetup.PageStartingNumber = startNumber;
            builder_operate.PageSetup.PageNumberStyle = ns;
            //頁碼在每個section會重新開始
            builder_operate.PageSetup.RestartPageNumbering = true;
            //頁碼位置
            builder_operate.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder_operate.InsertField("PAGE", "");
            builder_operate.MoveToDocumentEnd();
        }

 

11.移除最后的分頁符

public static void RemoveLastPageBreak(Document doc)
        {
            NodeCollection runs = doc.LastSection.GetChildNodes(NodeType.Run, true);
            
            for (int i = runs.Count - 1; i >= 0; i--)
            {
                Run run = (Run)runs[i];
                if (run.Text.IndexOf(ControlChar.PageBreakChar) >= 0)
                {
                    run.Text = run.Text.Remove(run.Text.IndexOf(ControlChar.PageBreakChar), 1);
                    break;
                }
            }
        }

12.插入目錄

/// <summary>
        /// 插入目錄
        /// </summary>
        /// <param name="bulider_blank"></param>
        public static void InsertTOC(DocumentBuilder bulider_blank)
        {
            //設置"目錄"格式
            bulider_blank.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            bulider_blank.Bold = true;
            bulider_blank.Font.Name = "SONG";
            bulider_blank.Writeln("目錄");
            bulider_blank.ParagraphFormat.ClearFormatting();//清除所有樣式
            bulider_blank.InsertTableOfContents("\\o\"1-3\"\\h\\z\\u");
            bulider_blank.InsertBreak(BreakType.SectionBreakNewPage);
        }

 

獲取某一Section的頁數

public static int getLastSectionPageCount(Document doc)
        {
            int idx = doc.Sections.IndexOf(doc.LastSection);
            Document tmp = doc.Clone();
            for (int i = tmp.Sections.Count - 1; i >= 0; i--)
            {
                if (i != idx)
                {
                    tmp.Sections.RemoveAt(i);
                }
            }
            return tmp.PageCount;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM