C#匯出word [無規則表結構+模板]

來源:互聯網
上載者:User

標籤:嵌套   eric   wpa   mis   selection   number   img   路徑   儲存格   

1)當然可以考慮使用aspose.word。使用書籤替換的方案替換模板中對應的書籤值。

2)但是我使用了Interop.Word,下面記錄使用類及要注意的地方

3)使用類

Report.cs 來自於網上 修改了在添加表格時焦點移動到最後並建立一頁
using System;using System.Collections.Generic;using System.Text;using Microsoft.Office.Interop.Word;namespace Song_Public //這邊需要換成自己的命名空間名{    public class Report    {        private _Application wordApp = null;        private _Document wordDoc = null;        public _Application Application        {            get            {                return wordApp;            }            set            {                wordApp = value;            }        }        public _Document Document        {            get            {                return wordDoc;            }            set            {                wordDoc = value;            }        }        //通過模板建立新文檔        public void CreateNewDocument(string filePath)        {            killWinWordProcess();            wordApp = new ApplicationClass();            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;            wordApp.Visible = false;            object missing = System.Reflection.Missing.Value;            object templateName = filePath;            wordDoc = wordApp.Documents.Open(ref templateName, ref missing,              ref missing, ref missing, ref missing, ref missing, ref missing,              ref missing, ref missing, ref missing, ref missing, ref missing,              ref missing, ref missing, ref missing, ref missing);        }        //儲存新檔案        public void SaveDocument(string filePath)        {            object fileName = filePath;            object format = WdSaveFormat.wdFormatDocument;//儲存格式            object miss = System.Reflection.Missing.Value;            wordDoc.SaveAs(ref fileName, ref format, ref miss,              ref miss, ref miss, ref miss, ref miss,              ref miss, ref miss, ref miss, ref miss,              ref miss, ref miss, ref miss, ref miss,              ref miss);            //關閉wordDoc,wordApp對象            object SaveChanges = WdSaveOptions.wdSaveChanges;            object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;            object RouteDocument = false;            wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);            wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);        }        //在書籤處插入值        public bool InsertValue(string bookmark, string value)        {            object bkObj = bookmark;            if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))            {                wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();                wordApp.Selection.TypeText(value);                return true;            }            return false;        }        //插入表格,bookmark書籤        public Table InsertTable(string bookmark, int rows, int columns, float width)        {            object miss = System.Reflection.Missing.Value;            object oStart = bookmark;            //Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置            // Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置            // wordApp.Selection.EndKey(6, 0);            wordApp.Selection.EndKey(WdUnits.wdStory);            wordApp.Selection.InsertNewPage();            //object start = 0;            //object end = 0;            //Range tableLocation = wordDoc.Range(ref start, ref end);            Table newTable = wordDoc.Tables.Add(wordApp.Selection.Range, rows, columns, ref miss, ref miss);            //設定表的格式            newTable.Borders.Enable = 1; //允許有邊框,預設沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度            if (width != 0)            {                newTable.PreferredWidth = width;//表格寬度            }            newTable.AllowPageBreaks = false;            //object oMissing = System.Reflection.Missing.Value;            //wordApp.Visible = true;            //wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);            //object start = 0;            //object end = 0;            //Microsoft.Office.Interop.Word.Range tableLocation = wordDoc.Range(ref start, ref end);            //Table newTable = wordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing);            return newTable;        }        /// <summary>        /// 添加一個新表 參考        /// </summary>        public  Table AddTable(int rows, int columns)        {            object oMissing = System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Application WordApp;            Microsoft.Office.Interop.Word.Document WordDoc;            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();            WordApp.Visible = true;            WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);            object start = 0;            object end = 0;            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end);            Table newTable = WordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing);//3行4列的表                                                                                                          //設定表的格式            newTable.Borders.Enable = 1; //允許有邊框,預設沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度            newTable.AllowPageBreaks = false;            return newTable;        }        //合併儲存格 表名,開始行號,開始列號,結束行號,結束列號        public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)        {            table.Cell(row1, column1).Merge(table.Cell(row2, column2));        }        //設定表格內容對齊Align水平方向,Vertical垂直方向(靠左對齊,置中對齊,靠右對齊分別對應Align和Vertical的值為-1,0,1)        public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, int Align, int Vertical)        {            switch (Align)            {                case -1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//靠左對齊                case 0: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平置中                case 1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//靠右對齊            }            switch (Vertical)            {                case -1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對齊                case 0: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直置中                case 1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對齊            }        }        //設定表格字型        public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)        {            if (size != 0)            {                table.Range.Font.Size = Convert.ToSingle(size);            }            if (fontName != "")            {                table.Range.Font.Name = fontName;            }        }        //是否使用邊框,n表格的序號,use是或否        public void UseBorder(int n, bool use)        {            if (use)            {                wordDoc.Content.Tables[n].Borders.Enable = 1; //允許有邊框,預設沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)            }            else            {                wordDoc.Content.Tables[n].Borders.Enable = 2; //允許有邊框,預設沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)            }        }        //給表格插入一行,n表格的序號從1開始記        public void AddRow(int n)        {            object miss = System.Reflection.Missing.Value;            wordDoc.Content.Tables[n].Rows.Add(ref miss);            wordDoc.Content.Tables[n].Rows.Height = 100;//設定新增加的這行表格的高度        }        //給表格添加一行        public void AddRow(Microsoft.Office.Interop.Word.Table table)        {            object miss = System.Reflection.Missing.Value;            table.Rows.Height = 40;            table.Rows.Add(ref miss);        }        //給表格插入rows行,n為表格的序號        public void AddRow(int n, int rows)        {            object miss = System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for (int i = 0; i < rows; i++)            {                table.Rows.Add(ref miss);            }        }        //給表格中儲存格插入元素,table所在表格,row行號,column列號,value插入的元素        public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)        {            table.Cell(row, column).Range.Text = value;        }        //給表格中儲存格插入元素,n表格的序號從1開始記,row行號,column列號,value插入的元素        public void InsertCell(int n, int row, int column, string value)        {            wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;        }        //給表格插入一行資料,n為表格的序號,row行號,columns列數,values插入的值        public void InsertCell(int n, int row, int columns, string[] values)        {            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for (int i = 0; i < columns; i++)            {                table.Cell(row, i + 1).Range.Text = values[i];            }        }        //插入圖片        public void InsertPicture(string bookmark, string picturePath, float width, float hight)        {            object miss = System.Reflection.Missing.Value;            object oStart = bookmark;            Object linkToFile = false;    //圖片是否為外部連結            Object saveWithDocument = true; //圖片是否隨文檔一起儲存            object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置            wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);            wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //設定圖片寬度            wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //設定圖片高度        }        //插入一段文字,text為文字內容        public void InsertText(string bookmark, string text)        {            object oStart = bookmark;            object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;            Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);            wp.Format.SpaceBefore = 6;            wp.Range.Text = text;            wp.Format.SpaceAfter = 24;            wp.Range.InsertParagraphAfter();            wordDoc.Paragraphs.Last.Range.Text = "\n";        }        //殺掉winword.exe進程        public void killWinWordProcess()        {            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");            foreach (System.Diagnostics.Process process in processes)            {                bool b = process.MainWindowTitle == "";                if (process.MainWindowTitle == "")                {                    process.Kill();                }            }        }    }}

  4)使用方式

          1)按書籤匯入值 書籤設定見下方

            Report report = new Report();            var path = System.Web.HttpContext.Current.Server.MapPath("/files/word/2.doc");            var savapath = System.Web.HttpContext.Current.Server.MapPath("/files/word/" + RandomStr.GetSerialNumber(4) + ".doc");            report.CreateNewDocument(path); //模板路徑            report.InsertValue("name", "世界盃");//在書籤“name”處插入值

    2)匯入表格 

Table table2 = report.InsertTable("table2", 4, 4, 0); //在書籤“table2”處插入2行3列行寬

    3)匯入表格式資料

report.InsertCell(table2, 1, 1, "項目名稱");//表名,行號,列號,值

   4)合併儲存格

report.MergeCell(table2, 1, 2, 1, 4); //表名,開始行號,開始列號,結束行號,結束列號 

  5)設定字型大小

report.SetFont_Table(table2, "宋體", 11);//宋體14磅

  6)文檔儲存

 report.SaveDocument(savapath);

  7)類中可修改的叮噹

  table.Rows.Height = 40; //添加行時可 修改當前行的高度AddRow方法
 //InsertTable方法修改回按書籤的位置來添加表格 此方法不適用多個表格的匯出
 public Table InsertTable(string bookmark, int rows, int columns, float width)        {            object miss = System.Reflection.Missing.Value;            object oStart = bookmark;            Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置            Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);            //設定表的格式            newTable.Borders.Enable = 1; //允許有邊框,預設沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度            if (width != 0)            {                newTable.PreferredWidth = width;//表格寬度            }            newTable.AllowPageBreaks = false;            return newTable;        }

  

wordApp.Selection.EndKey(WdUnits.wdStory);//焦點放到文檔最後

5)注意點 

     1)表格匯出時會巢狀表格 

                原因 :表格匯入完成後 焦點的位置預設會在表格裡 在次插入會導致在表格內嵌套  

                解決:把焦點放到文檔末尾 wordApp.Selection.EndKey(WdUnits.wdStory);

    2)合并時會報所要求的的成員不存在

                原因:表格前一項合并完 多列合成一列 後面再用之前的列值來合并。肯定找不到 

                解決:先輸出對應的列與值,最後在處理合并。每次合并都記錄,當前行的合并列數 如下

                    //處理合并                    var pans = 0;//合并數                    foreach (var o in lo)   //lo為一個list<other>                        {                        report.MergeCell(table2, o.row, o.col1-pans, o.row, o.col2- pans);                        pans++;                    }

  3)書籤的插入

word->插入->書籤->輸入書籤名稱->添加  

 

C#匯出word [無規則表結構+模板]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.