1. 程式人生 > >NPOI建立DOCX常用操作【轉】

NPOI建立DOCX常用操作【轉】

1、  建立文件

XWPFDocument m_Docx = 
new XWPFDocument();
2、  頁面設定

//1‘=1440twip=25.4mm=72pt(磅point)=96px(畫素pixel)
          //1px(畫素pixel)=0.75pt(磅point)
// A4:W=11906 twip=8.269''=210mm,h=16838twip=11.693''=297mm
          //A5:W=8390 twip=5.827''=148mm,h=11906 twip=8.269''=210mm
          //A6:W=5953 twip=4.134''=105mm,h=8390twip=5.827''=1148mm
           //16k195mmX270mm:
           //16k184mmX260mm:
           //16k197mmX273mm:
           CT_SectPr m_SectPr =
newCT_SectPr();

           //頁面設定A4橫向
m_SectPr.pgSz.w = (ulong)16838;
          m_SectPr.pgSz.h = (ulong)11906;
          m_Docx.Document.body.sectPr = m_SectPr; 
3、  建立段落

1) XWPFParagraph gp = m_Docx.CreateParagraph();
2)      CT_Pm_p = m_Docx.Document.body.AddNewP();
           m_p.AddNewPPr().AddNewJc().val = 
ST_Jc.center;//段落水平居中
XWPFParagraph gp =
newXWPFParagraph(m_p, m_Docx); //建立XWPFParagraph
4、  段首行縮排

gp.IndentationFirstLine=(int)100;
可以用一個函式計算
protected 
int Indentation(Stringfontname, 
int fontsize, int Indentationfonts, 
FontStylefs)
    {
            //字顯示寬度,用於段首行縮排
//字號與fontsize關係
//初號(0號)=84,小初=72,1號=52,2號=44,小2=36,3號=32,小3=30,4號=28,
//小4=24,5號=21,小5=18,6號=15,小6=13,7號=11,8號=10
       Graphicsm_tmpGr = 
this.CreateGraphics();
        m_tmpGr.PageUnit = GraphicsUnit.Point;
         SizeF size = m_tmpGr.MeasureString("好",
new Font(fontname,fontsize * 0.75F, fs));
         return (int)size.Width* Indentationfonts * 10;
   }

gp.IndentationFirstLine= Indentation("宋體", 21, 2,
FontStyle.Regular);//段首行縮排2字元


5、  行距設定

//單倍為預設值(240twip)不需設定,1.5倍=240X1.5=360twip,2倍=240X2=480twip

m_p.AddNewPPr().AddNewSpacing().line = "400";//行距固定20磅

m_p.AddNewPPr().AddNewSpacing().lineRule= 
ST_LineSpacingRule.exact; 
6、  建立RUN

        1)  XWPFRun gr= gp.CreateRun();
           gr.GetCTR().AddNewRPr().AddNewRFonts().ascii = 
"黑體";
gr.GetCTR().AddNewRPr().AddNewRFonts().eastAsia = 
"黑體";
gr.GetCTR().AddNewRPr().AddNewRFonts().hint = 
ST_Hint.eastAsia;
gr.GetCTR().AddNewRPr().AddNewSz().val = (ulong)44;//2號字型
gr.GetCTR().AddNewRPr().AddNewSzCs().val = (ulong)44;
           gr.GetCTR().AddNewRPr().AddNewB().val = 
true;//加粗
gr.GetCTR().AddNewRPr().AddNewColor().val= 
"red";//字型顏色
gr.SetText("DOCX表");
2) CT_R= m_p.AddNewR();
7、  建立表

1)  建立表

有兩種方法:

a.方法1

XWPFTabletable = m_Docx.CreateTable(1, 1);//建立1行1列表
CT_Tblm_CTTbl = m_Docx.Document.body.GetTblArray()[0];//獲得文件第一張表
b.方法2
CT_Tblm_CTTbl = m_Docx.Document.body.AddNewTbl();
XWPFTabletable = 
new XWPFTable(m_CTTbl,m_Docx);//建立1行1列表
2)  表水平居中

m_CTTbl.AddNewTblPr().jc = new 
CT_Jc();
m_CTTbl.AddNewTblPr().jc.val = ST_Jc.center;//表在頁面水平居中
3)  表寬度 

m_CTTbl.AddNewTblPr().AddNewTblW().w = 
"2000";//表寬度
m_CTTbl.AddNewTblPr().AddNewTblW().type = 
ST_TblWidth.dxa;
4)  表定位

//若tblpXSpec、tblpX同時存在,則tblpXSpec優先tblpX;

//若tblpYSpec、tblpY同時存在,則tblpYSpec優先tblpY;

m_CTTblPr.tblpPr = new 
CT_TblPPr();//表定位
m_CTTblPr.tblpPr.tblpX = "4003";//表左上角座標
m_CTTblPr.tblpPr.tblpY = "365";
//m_CTTblPr.tblpPr.tblpXSpec = ST_XAlign.center;// tblpXSpec優先tblpX
//m_CTTblPr.tblpPr.tblpYSpec = ST_YAlign.top;// tblpYSpec優先tblpY
m_CTTblPr.tblpPr.leftFromText = (ulong)180;
m_CTTblPr.tblpPr.rightFromText = (ulong)180;
m_CTTblPr.tblpPr.vertAnchor = ST_VAnchor.text;
m_CTTblPr.tblpPr.horzAnchor = ST_HAnchor.page;
5)  列寬設定

//列寬設定
CT_TcPr m_Pr =table.GetRow(0).GetCell(0).GetCTTc().AddNewTcPr();
m_Pr.tcW = new 
CT_TblWidth();
m_Pr.tcW.w = "1500";//單元格寬
m_Pr.tcW.type = ST_TblWidth.dxa;
m_Pr = table.GetRow(0).GetCell(1).GetCTTc().AddNewTcPr();
m_Pr.tcW = new 
CT_TblWidth();
m_Pr.tcW.w = "1000";//單元格寬
m_Pr.tcW.type = ST_TblWidth.dxa;
6)  建立行

a. XWPFTableRow m_Row = table.CreateRow();//建立一行
b. XWPFTableRow m_Row = table.InsertNewTableRow(0);//表頭插入一行
c. XWPFTableRow td3 = table.InsertNewTableRow(table.Rows.Count - 1);//插入行
d. CT_Row m_NewRow = 
new CT_Row();
XWPFTableRow  m_Row = 
new XWPFTableRow(m_NewRow, table);
table.AddRow(m_Row);
7)  行高設定

a. m_Row.GetCTRow().AddNewTrPr().AddNewTrHeight().val= (ulong)426;

b. m_NewRow.AddNewTrPr().AddNewTrHeight().val= (ulong)426;
8)  建立單元格

a.      XWPFTableCell cell = m_Row.CreateCell();//建立一單元格,建立單元格時就建立了一個CT_P
b.      XWPFTableCell cell = m_Row.AddNewTableCell();//建立單元格時建立了一個CT_P
9)  單元格設定文字

table.GetRow(0).GetCell(0).SetText("111");
10)  列合併

//表增加行,合併列
CT_Row m_NewRow = 
new CT_Row();  
XWPFTableRow m_Row = 
new XWPFTableRow(m_NewRow,table);
table.AddRow(m_Row);
XWPFTableCell cell = m_Row.CreateCell();
CT_Tc cttc = cell.GetCTTc();
CT_TcPr ctPr = cttc.AddNewTcPr();
ctPr.gridSpan = new 
CT_DecimalNumber();
ctPr.gridSpan.val = "3"; //合併3列
cttc.GetPList()[0].AddNewPPr().AddNewJc().val = 
ST_Jc.center;
cttc.GetPList()[0].AddNewR().AddNewT().Value = 
"sss";
11)  行合併

//1行
CT_Row m_NewRow = 
new CT_Row();
XWPFTableRow m_Row = 
new XWPFTableRow(m_NewRow,table);
table.AddRow(m_Row);
XWPFTableCell cell = m_Row.CreateCell();
CT_Tc cttc = cell.GetCTTc();
CT_TcPr ctPr = cttc.AddNewTcPr();
ctPr.AddNewVMerge().val = ST_Merge.restart;//合併行
ctPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直
cttc.GetPList()[0].AddNewPPr().AddNewJc().val = 
ST_Jc.center;
cttc.GetPList()[0].AddNewR().AddNewT().Value = 
"xxx";
//2行,多行合併類似
m_NewRow = new 
CT_Row();
m_Row = new 
XWPFTableRow(m_NewRow,table);
table.AddRow(m_Row);
cell = m_Row.CreateCell();
cttc = cell.GetCTTc();
ctPr = cttc.AddNewTcPr();
ctPr.AddNewVMerge().val =

[email protected];//合併行


8、  插圖

1)  內聯式插圖(inline)

此種插圖方式對插入的圖片位置不能靈活控制,只能通過段設定,對應word的嵌入型插圖。寬和高數值換算:1cm=360000 EMUS(English Metric Unit)。



FileStream gfs = 
null;
gfs = new 
FileStream("f:\\pic\\1.jpg", 
FileMode.Open, FileAccess.Read);
m_p = m_Docx.Document.body.AddNewP();
m_p.AddNewPPr().AddNewJc().val = ST_Jc.center;//段落水平居中
gp = new 
XWPFParagraph(m_p,m_Docx);
gr = gp.CreateRun();
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG,
"1.jpg",1000000, 1000000);
gfs.Close();
2)  錨式插圖(anchor)

此種插圖方式對插入的圖片位置能靈活控制,對應word的四周型、緊密型、穿越型等。圖的左上角座標及寬和高數值換算:1cm=360000 EMUS(English Metric Unit)。

gfs = new 
FileStream("f:\\pic\\1.jpg", 
FileMode.Open, FileAccess.Read);
m_p = m_Docx.Document.body.AddNewP();
m_p.AddNewPPr().AddNewJc().val = ST_Jc.center;
gp = new 
XWPFParagraph(m_p,m_Docx);
gr = gp.CreateRun();

CT_Anchor an = 
newCT_Anchor();
//圖片距正文上(distT)、下(distB)、左(distL)、右(distR)的距離。114300EMUS=3.1mm
an.distB = (uint)(0);
an.distL = 114300u;
an.distR = 114300U;
an.distT = 0U;
an.relativeHeight = 251658240u;
an.behindDoc = false; 
//"0",圖與文字的上下關係
an.locked = false;  
//"0"
an.layoutInCell = true;  
//"1"
an.allowOverlap = true;  
//"1" 

CT_Positive2D simplePos = 
new CT_Positive2D();
simplePos.x = (long)0;
simplePos.y = (long)0;
CT_EffectExtent effectExtent =
new CT_EffectExtent();
effectExtent.b = 0L;
effectExtent.l = 0L;
effectExtent.r = 0L;
effectExtent.t = 0L;
           //圖左上角座標
CT_PosH posH = 
newCT_PosH();
          posH.relativeFrom = ST_RelFromH.column;
          posH.posOffset = 4000000;//單位:EMUS,1CM=360000EMUS
           CT_PosV posV = 
newCT_PosV();
          posV.relativeFrom = ST_RelFromV.paragraph;
          posV.posOffset = 200000;

a)      四周型

CT_WrapSquare wrapSquare = 
new CT_WrapSquare();
wrapSquare.wrapText = ST_WrapText.bothSides;
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG,
"1.jpg",1000000, 1000000,
posH, posV, wrapSquare,anchor,simplePos,effectExtent);
b)      緊密型

CT_WrapTight wrapTight = 
new CT_WrapTight();
wrapTight.wrapText = ST_WrapText.bothSides;
wrapTight.wrapPolygon = new 
CT_WrapPath();
wrapTight.wrapPolygon.edited = false;
wrapTight.wrapPolygon.start = new
CT_Positive2D();
wrapTight.wrapPolygon.start.x = 0;
wrapTight.wrapPolygon.start.y = 0;
CT_Positive2D lineTo = 
new CT_Positive2D();
wrapTight.wrapPolygon.lineTo = new
List<CT_Positive2D>();
lineTo = new 
CT_Positive2D();
lineTo.x = 0;
lineTo.y = 21394;
wrapTight.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 21806;
lineTo.y = 21394;
wrapTight.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 21806;
lineTo.y = 0;
wrapTight.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 0;
lineTo.y = 0;
wrapTight.wrapPolygon.lineTo.Add(lineTo);
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG,
"1.jpg",720000, 720000,
posH, posV, wrapTight, anchor, simplePos, effectExtent);
c)      穿越型

CT_WrapThrough wrapThrough = 
new CT_WrapThrough();
wrapThrough.wrapText = ST_WrapText.bothSides;
wrapThrough.wrapPolygon = new 
CT_WrapPath();
wrapThrough.wrapPolygon.edited = false;
wrapThrough.wrapPolygon.start = new
CT_Positive2D();
wrapThrough.wrapPolygon.start.x = 0;
wrapThrough.wrapPolygon.start.y = 0;
CT_Positive2D lineTo = 
new CT_Positive2D();
wrapThrough.wrapPolygon.lineTo = new
List<CT_Positive2D>();
lineTo = new 
CT_Positive2D();
lineTo.x = 0;
lineTo.y = 21394;
wrapThrough.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 21806;
lineTo.y = 21394;
wrapThrough.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 21806;
lineTo.y = 0;
wrapThrough.wrapPolygon.lineTo.Add(lineTo);
lineTo = new 
CT_Positive2D();
lineTo.x = 0;
lineTo.y = 0;
wrapThrough.wrapPolygon.lineTo.Add(lineTo);
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG,
"1.jpg",720000, 720000, 
posH, posV, wrapThrough, anchor, simplePos, effectExtent);
9、  頁首頁尾設定

1)  頁首設定
XWPFDocument m_Docx = 
new XWPFDocument();
m_Docx.Document.body.sectPr = new
CT_SectPr();
CT_SectPr m_SectPr =m_Docx.Document.body.sectPr;
//建立頁首
CT_Hdr m_Hdr = 
new CT_Hdr();
m_Hdr.AddNewP().AddNewR().AddNewT().Value = 
"hhh";//頁首內容
//建立頁首關係(headern.xml)
XWPFRelation Hrelation = 
XWPFRelation.HEADER;
XWPFHeader m_h = (XWPFHeader)m_Docx.CreateRelationship(Hrelation,XWPFFactory.GetInstance(),
m_Docx.HeaderList.Count + 1);
//設定頁首
m_h.SetHeaderFooter(m_Hdr);
CT_HdrFtrRef m_HdrFtr =m_SectPr.AddNewHeaderReference();
m_HdrFtr.type =
[email protected]
;
m_HdrFtr.id = m_h.GetPackageRelationship().Id;
2)  頁尾設定
XWPFDocument m_Docx = 
new XWPFDocument();
//頁面設定
m_Docx.Document.body.sectPr = new
CT_SectPr();
CT_SectPr m_SectPr =m_Docx.Document.body.sectPr;
//建立頁尾
CT_Ftr m_ftr = 
new CT_Ftr();
m_ftr.AddNewP().AddNewR().AddNewT().Value = 
"fff";//頁尾內容
//建立頁尾關係(footern.xml)
XWPFRelation Frelation = 
XWPFRelation.FOOTER;
XWPFFooter m_f = (XWPFFooter)m_Docx.CreateRelationship(Frelation,XWPFFactory.GetInstance(),
m_Docx.FooterList.Count + 1);
//設定頁尾
m_f.SetHeaderFooter(m_ftr);
CT_HdrFtrRef m_HdrFtr =m_SectPr.AddNewFooterReference();
m_HdrFtr.type =
[email protected]
;
m_HdrFtr.id = m_f.GetPackageRelationship().Id;
10、             腳註尾註

建立腳註和尾註,首先要設定格式,其次建立腳註和尾註內容,最後在正文中標註。

1)  格式設定

在正文中標註腳註採用阿拉伯數字且為上標,而標註尾註採用羅馬數字且為上標,在word中可以事先用格式儲存在格式xml中,以後可以在正文引用其格式即可。

建立格式檔案(styles.xml):XWPFStyles m_styles = m_Docx.CreateStyles();
建立格式xml:CT_Styles m_ctstyles =
new CT_Styles();可以根據需要建立相應的格式。在此只列舉與腳註有關的格式a6和a7。
格式a6設定如下,其中需要格式a和Char2。
//footnote text
           m_ctstyle = new 
CT_Style();
           m_ctstyle.type = ST_StyleType.paragraph;
           m_ctstyle.customStyle = ST_OnOff.True;
           m_ctstyle.styleId = "a6";
           m_ctstyle.name = new 
CT_String();
           m_ctstyle.name.val = "footnotetext";
           m_ctstyle.basedOn = new
CT_String();
           m_ctstyle.basedOn.val = "a";
           m_ctstyle.link = new 
CT_String();
           m_ctstyle.link.val = "Char2";
           m_ctstyle.uiPriority = new
CT_DecimalNumber();
           m_ctstyle.uiPriority.val = 
"99";
           m_ctstyle.semiHidden = new
CT_OnOff();
           m_ctstyle.semiHidden.val = true;
           m_ctstyle.unhideWhenUsed = new
CT_OnOff();
           m_ctstyle.unhideWhenUsed.val = 
true;
           m_ctstyle.rsid = new 
CT_LongHexNumber();
            byte[] m_bytefootnoteText = { 0x00, 0xF0, 0x43, 0x96};
           m_ctstyle.rsid.val = m_bytefootnoteText;
           m_ctstyle.pPr = new 
CT_PPr();
           m_ctstyle.pPr.snapToGrid = new
CT_OnOff();
            m_ctstyle.pPr.snapToGrid.val= 
false;
           m_ctstyle.pPr.jc = new
CT_Jc();
           m_ctstyle.pPr.jc.val = ST_Jc.left;
           m_ctstyle.rPr = new 
CT_RPr();
           m_ctstyle.rPr.sz = new
CT_HpsMeasure();
           m_ctstyle.rPr.sz.val = 18;
           m_ctstyle.rPr.szCs = new
CT_HpsMeasure();
           m_ctstyle.rPr.szCs.val = 18;
           m_ctstyles.style.Add(m_ctstyle);
格式a7設定如下,其中需要格式a0。
//footnote reference
           m_ctstyle = new 
CT_Style();
            m_ctstyle.type= ST_StyleType.character;
           m_ctstyle.styleId = "a7";
           m_ctstyle.name = new 
CT_String();
           m_ctstyle.name.val = "footnotereference";
           m_ctstyle.basedOn = new
CT_String();
            m_ctstyle.basedOn.val= "a0";
           m_ctstyle.uiPriority = new
CT_DecimalNumber();
           m_ctstyle.uiPriority.val = 
"99";
           m_ctstyle.semiHidden = new
CT_OnOff();
           m_ctstyle.semiHidden.val = true;
           m_ctstyle.unhideWhenUsed = new
CT_OnOff();
           m_ctstyle.unhideWhenUsed.val = 
true;
           m_ctstyle.rsid = new 
CT_LongHexNumber();
           m_ctstyle.rsid.val = m_bytefootnoteText;
           m_ctstyle.rPr = new 
CT_RPr();
           m_ctstyle.rPr.vertAlign = new
CT_VerticalAlignRun();
           m_ctstyle.rPr.vertAlign.val = 
ST_VerticalAlignRun.superscript;
           m_ctstyles.style.Add(m_ctstyle);    
把格式新增到格式檔案中:m_styles.SetStyles(m_ctstyles);
2)  腳註

a.      建立腳註內容

實際上腳註內容的格式就是引用前面所述的格式設定中的定義,即格式a6和a7。

建立腳註內容檔案:XWPFFootnotes m_ftns =m_Docx.CreateFootnotes()。
//建立腳註內容
int Id =m_ftns.GetFootnotesList().Count;
               CT_FtnEdn m_ftnedn =
new CT_FtnEdn();
               m_ftnedn.id = Id.ToString();
               CT_P m_FtnEdnxmlP =m_ftnedn.AddNewP();
               CT_PPr m_FtnEdnxmlPPr =m_FtnEdnxmlP.AddNewPPr();
               m_FtnEdnxmlPPr.AddNewPStyle().val = 
"a6";
               m_FtnEdnxmlPPr.AddNewRPr().rFonts = 
new CT_Fonts();
               m_FtnEdnxmlPPr.AddNewRPr().rFonts.hint = 
ST_Hint.eastAsia;
               CT_R m_FtnEdnxmlR =m_FtnEdnxmlP.AddNewR();
               m_FtnEdnxmlR.AddNewRPr().rStyle = 
new CT_String();
               m_FtnEdnxmlR.AddNewRPr().rStyle.val = 
"a7";
               m_FtnEdnxmlR.Items = newSystem.Collections.ArrayList();
               m_FtnEdnxmlR.Items.Add(new
CT_Empty());
               m_FtnEdnxmlR.ItemsElementName = 
new List<RunItemsChoiceType>();
               m_FtnEdnxmlR.ItemsElementName.Add(RunItemsChoiceType.footnoteRef);
               m_FtnEdnxmlR = m_FtnEdnxmlP.AddNewR();
               m_FtnEdnxmlR.AddNewT().Value = 
" ";
               m_FtnEdnxmlR = m_FtnEdnxmlP.AddNewR();
               m_FtnEdnxmlR.AddNewT().Value = strFtnEdn; 
//"腳註test內容
XWPFFootnotem_fn = m_ftns.AddFootnote(m_ftnedn);
b.      在正文中標註

最好用CT_P m_p = m_Docx.Document.body.AddNewP();方式建立段,在m_p中可以不斷建立CT_R。
CT_R m_r = m_p.AddNewR();  
m_r.AddNewT().Value = "NPOI";
//標註腳註
CT_R m_FtnEdnR = m_p.AddNewR();
         m_FtnEdnR.AddNewRPr().rStyle= new
CT_String();
        m_FtnEdnR.AddNewRPr().rStyle.val = 
"a7";
        m_FtnEdnR.Items = newSystem.Collections.ArrayList();
         CT_FtnEdnRef m_ftnref =
newCT_FtnEdnRef();
        m_ftnref.id = m_FtnId;//建立腳註內容得到的Id
        m_FtnEdnR.Items.Add(m_ftnref);
        m_FtnEdnR.ItemsElementName = new
List<RunItemsChoiceType>();
        m_FtnEdnR.ItemsElementName.Add(RunItemsChoiceType.footnoteReference);
        m_r =m_p.AddNewR();
        m_r.AddNewT().Value= "……";
3)  尾註

NPOI中的OpenXmlFormats提供了較為完善的尾註所有功能,但在XWPF中沒有提供建立尾註的方法。



11、             超連結書籤

利用NPOI建立超連結書籤分兩個步驟。一是建立與書籤關聯的超連結;二是建立書籤。

1)  建立與書籤關聯的超連結

NPOI提供兩種超連結,一種是超連結到另一檔案;另一種是超連結到書籤。下面僅介紹建立超連結到書籤的方法。

建立文件:XWPFDocument m_Docx =
new XWPFDocument();
建立段落:CT_P m_p = m_Docx.Document.body.AddNewP();
建立超連結集合:m_p.Items = newSystem.Collections.ArrayList();
建立超連結:
CT_Hyperlink1 m_hyperlink =
new CT_Hyperlink1();
           m_hyperlink.anchor = "NPOI1";//書籤名
m_hyperlink.history = ST_OnOff.True;
           m_hyperlink.Items = newSystem.Collections.ArrayList();
            CT_R m_r = 
new CT_R();
           m_r.AddNewT().Value = "書籤1";
           m_hyperlink.Items.Add(m_r);
           m_hyperlink.ItemsElementName = 
new List<ItemsChoiceType12>();
            m_hyperlink.ItemsElementName.Add(ItemsChoiceType12.hyperlink);
           m_p.Items.Add(m_hyperlink);
2)  建立書籤

書籤分開始和結束兩部分組成。

//書籤0開始

int m_bookId = 0;//同一段內有多個書籤,需要不同的Id,不同段的書籤Id可以相同
m_p= m_Docx.Document.body.AddNewP();
            m_p.AddNewPPr().AddNewJc().val= 
ST_Jc.both;
           m_p.AddNewPPr().AddNewSpacing().line = 
"400";//固定行距20磅
m_p.AddNewPPr().AddNewSpacing().lineRule = 
ST_LineSpacingRule.exact;
           m_p.Items = new System.Collections.ArrayList();
            CT_Bookmark m_ctbook1 =
newCT_Bookmark();
           m_bookId = m_p.Items.Count;
           m_ctbook1.id = m_bookId.ToString(); 
//"0";
           m_ctbook1.name = "NPOI1";//書籤名,超連結用
m_p.Items.Add(m_ctbook1);
           m_p.ItemsElementName = new
List<ParagraphItemsChoiceType>();
           m_p.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkStart);
           m_p.AddNewR().AddNewT().Value = 
"1、NPOI介紹";
            //書籤0結束
m_ctbook1 = new 
CT_Bookmark();
           m_ctbook1.id = m_bookId.ToString();//"0";
           m_p.Items.Add(m_ctbook1);
           m_p.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkEnd);


12、             插入圖表

在docx中插入圖表分三步實現。一是建立xlsx格式的圖表原始資料,二是建立圖表型別,三是在正文中插入圖表。每一個圖表對應一個xlsx檔案,下面以餅圖為例說明。

1)      建立xlsx格式的圖表原始資料

//建立xlsx

                   XSSFWorkbook workbook = newXSSFWorkbook();

         //建立表單1(餅圖)

I       Sheet sheet =workbook.CreateSheet("Sheet1");

                   //表單1餅圖資料

//銷售額

//第一季度 8.2

           //第二季度 3.2

           //第三季度 1.4

           //第四季度 1.2

           IRow row = sheet.CreateRow(0);

           ICell cell = row.CreateCell(0);

           cell = row.CreateCell(0);

           cell = row.CreateCell(1);

           cell.SetCellValue("銷售額");

row = sheet.CreateRow(1);

           cell = row.CreateCell(0);

           cell.SetCellValue("第一季度");

cell = row.CreateCell(1);

           cell.SetCellValue(8.2);

           row = sheet.CreateRow(2);

           cell = row.CreateCell(0);

           cell.SetCellValue("第二季度");

cell = row.CreateCell(1);

           cell.SetCellValue(3.2);

           row = sheet.CreateRow(3);

           cell = row.CreateCell(0);

           cell.SetCellValue("第三季度");

cell = row.CreateCell(1);

           cell.SetCellValue(1.4);

           row = sheet.CreateRow(4);

           cell = row.CreateCell(0);

           cell.SetCellValue("第四季度");

cell = row.CreateCell(1);

           cell.SetCellValue(1.2);

2)      建立圖表型別

//建立\word\charts\chartn.xml內容(簡單餅圖)

CT_ChartSpace ctpiechartspace = new CT_ChartSpace();

           ctpiechartspace.date1904 = new CT_Boolean();

           ctpiechartspace.date1904.val = 1;

           ctpiechartspace.lang = new CT_TextLanguageID();

           ctpiechartspace.lang.val = "zh-CN";

           CT_Chart m_chart = ctpiechartspace.AddNewChart();

           m_chart.plotArea = new CT_PlotArea();

           m_chart.plotArea.pieChart = new List<CT_PieChart>();

           //餅圖

CT_PieChart m_piechart = new CT_PieChart();

           m_piechart.varyColors = new CT_Boolean();

           m_piechart.varyColors.val = 1;

           m_piechart.ser = new List<CT_PieSer>();

           CT_PieSer m_pieser = new CT_PieSer();

           //標題

m_pieser.tx = new CT_SerTx();

           m_pieser.tx.strRef = new CT_StrRef();

           m_pieser.tx.strRef.f = "Sheet1!$B$1";

           m_pieser.tx.strRef.strCache = new CT_StrData();

           m_pieser.tx.strRef.strCache.ptCount = new CT_UnsignedInt();

           m_pieser.tx.strRef.strCache.ptCount.val = 1;

           CT_StrVal m_strval = new CT_StrVal();

           m_strval.idx = 0;

           m_strval.v = "銷售額";

m_pieser.tx.strRef.strCache.pt = new List<CT_StrVal>();

           m_pieser.tx.strRef.strCache.pt.Add(m_strval); 

           //行標題

m_pieser.cat = new CT_AxDataSource();

           m_pieser.cat.strRef = new CT_StrRef();

           m_pieser.cat.strRef.f = "Sheet1!$A$2:$A$5";

           m_pieser.cat.strRef.strCache = new CT_StrData();

           m_pieser.cat.strRef.strCache.ptCount = new CT_UnsignedInt();

           m_pieser.cat.strRef.strCache.ptCount.val = 4;

           m_pieser.cat.strRef.strCache.pt = new List<CT_StrVal>();

           m_strval = new CT_StrVal();

           m_strval.idx = 0;

           m_strval.v = "第一季度";

m_pieser.cat.strRef.strCache.pt.Add(m_strval);

           m_strval = new CT_StrVal();

           m_strval.idx = 1;

           m_strval.v = "第二季度";

m_pieser.cat.strRef.strCache.pt.Add(m_strval);

           m_strval = new CT_StrVal();

           m_strval.idx = 2;

           m_strval.v = "第三季度";

m_pieser.cat.strRef.strCache.pt.Add(m_strval);

           m_strval = new CT_StrVal();

           m_strval.idx = 3;

           m_strval.v = "第四季度";

m_pieser.cat.strRef.strCache.pt.Add(m_strval);

           //值

m_pieser.val = new CT_NumDataSource();

           m_pieser.val.numRef = new CT_NumRef();

           m_pieser.val.numRef.f = "Sheet1!$B$2:$B$5";

           m_pieser.val.numRef.numCache = new CT_NumData();

           m_pieser.val.numRef.numCache.formatCode = "General";

           m_pieser.val.numRef.numCache.ptCount = new CT_UnsignedInt();

           m_pieser.val.numRef.numCache.ptCount.val = 4;

           m_pieser.val.numRef.numCache.pt = new List<CT_NumVal>();

           CT_NumVal m_numval = new CT_NumVal();

           m_numval.idx = 0;

           m_numval.v = "8.2";

           m_pieser.val.numRef.numCache.pt.Add(m_numval);

           m_numval = new CT_NumVal();

           m_numval.idx = 1;

           m_numval.v = "3.2";

           m_pieser.val.numRef.numCache.pt.Add(m_numval);

           m_numval = new CT_NumVal();

           m_numval.idx = 2;

           m_numval.v = "1.4";

           m_pieser.val.numRef.numCache.pt.Add(m_numval);

           m_numval = new CT_NumVal();

           m_numval.idx = 3;

           m_numval.v = "1.2";

           m_pieser.val.numRef.numCache.pt.Add(m_numval); 

           m_piechart.ser.Add(m_pieser);

           m_chart.plotArea.pieChart.Add(m_piechart);

           m_chart.legend = new CT_Legend();

           m_chart.legend.legendPos = new CT_LegendPos();

           m_chart.legend.legendPos.val = ST_LegendPos.r;

           m_chart.plotVisOnly = new CT_Boolean();

           m_chart.plotVisOnly.val = 1;

3)      頁面中插入圖表

以inline式為例。

XWPFParagraph gp = m_Docx.CreateParagraph();

           XWPFRun gr = gp.CreateRun();

           gp = m_Docx.CreateParagraph();

           gr = gp.CreateRun();

           gr.AddChartSpace(workbook , ctpiechartspace, 5274310, 3076575);

NPOI是tonyqus提供的2.1.1.0原始碼經過新修改編譯。