close

這次又寫了一個程式來產生文件報表、公文。這回需要的是產生word裡面的form(表格)

且需要畫出各種特殊的形狀

且每個格子的格式都不大一樣(有些要分散對齊,有些要靠左對齊,有些則要置中對齊,字體大小也不盡相同)

如下圖:

form example

這邊看到了,每一個格子的設定都不大一樣,而且所需要的表格也不是什麼標準的10*10表格

我在這邊

是使用先

1、create 表格,再

2、把設定每一個欄位的寬度

3、把格子用「合併」的方式,來完成我所需要的效果

4、把每一個格子填入我要的資訊,並設定我要的效果

以下會一段一段的解釋這四個東西

----------------------------------------------------

先複習一下,怎麼在C#裡面產生一個word表格

1、要灌.NET framework 2.0 以上

2、要灌O2003PIA   <--不知道這個是什麼的,請按此到微軟網站下載

3、要在Project-Reference裡面加入
         Microsoft.Office.Core; 
         Microsoft.Office.Interop;  兩個東西

 

開啟WORD:

         Microsoft.Office.Interop.Word.ApplicationClass oWord = new Word.ApplicationClass();
            oWord.Visible = true;
            Word.Documents oDocs = oWord.Documents;

            object oMissing = System.Reflection.Missing.Value;
            Word._Document oDoc = oDocs.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            //設定邊界
            oDoc.PageSetup.TopMargin =    (float)(34);       //需為1.2cm
            oDoc.PageSetup.BottomMargin = (float)(34);      //    1.2cm
            oDoc.PageSetup.LeftMargin =   (float)(28.4);        //    1
            oDoc.PageSetup.RightMargin =  (float)(42.5);       //    1.5

------------------------------------------------------

1、Create表格

Range range = createFinalWorkRange(oDoc) ; //這行是用來取一個range的。
            object missing = System.Reflection.Missing.Value;
            Word.Table table;

            table = range.Tables.Add(range, 19, 8, ref missing, ref missing);// insert a table
                                       //創造一個19*8的table

            table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;    //設定內部框線為「單條線」
            table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;  //設定外部框線為「單條線」

接著,就可以對這個Table做一些動作了

 

2、設定欄位的長寬:

        //設定各欄位的寬度

         table.Columns[1].Width = 85f;
         table.Rows[4].Height = 51f;  

這是用來設定每一個不同row, column的長寬的方式~ 可以用來設定高度,還有寬度

記得columns只能設定寬度

rows只能設定長度喔

3、把格子用「合併」的方式,來完成我所需要的效果

            table.Cell(1, 8).Merge(table.Cell(3, 8));  //將(1,8),(2,8),(3,8)合併
            table.Cell(1, 7).Merge(table.Cell(3, 7));
            table.Cell(1, 6).Merge(table.Cell(2, 6));

 

結合2跟3,就可以畫出各種我們想要的格子了。

 

4、把每一個格子填入我要的資訊,並設定我要的效果

 table.Cell(1, 1).Range.Text = "姓名";  //設定文字

 table.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphDistribute;  //設定為分散對齊
                                                .wdAlignParagraphCenter      //置中對齊
                                                .wdAlignParagraphLeft           //靠左對齊

table.Cell(1, 1).Range.Font.Size = 10;//設定字體大小
 table.Cell(1, 1).Range.Font.Name = "標楷體";//設定字型

 

------------

另外:針對整個table也可以做動作喔

table.Select();
 wordApp.Selection.Font.Name = "標楷體";
 wordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //將其設為靠中間

 

---

以上則是表格使用的方法,謝謝大家的指教

arrow
arrow
    全站熱搜

    ccas 發表在 痞客邦 留言(7) 人氣()