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 = ST_Merge.@continue;//合並行
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 = ST_HdrFtr.@default;
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 = ST_HdrFtr.@default;
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源碼經過新修改編譯。
測試例子下載:http://download.csdn.net/detail/gltide/8016349。例中提供了創建表、插圖和圖表實現的代碼。
轉載自:http://blog.csdn.net/gltide/article/details/39929259
程序員的基礎教程:菜鳥程序員