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源码经过新修改编译。

时间: 2024-11-06 07:50:21

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''=

linux之常用操作、基本命令

目录 linux准备 centos下载地址 window下安装VMWare WMWare中安装centos centos系统准备 linux相关说明 linux常用目录结构 网络配置 yum仓库配置 常用操作/命令 安装命令方式 lrzsz lrzsz服务说明 安装lrzsz服务 lrzsz服务使用 ifconfig ifconfig说明 安装ifconfig ifconfig使用 ping hostname 修改主机名 service service命令格式 chkconfig Linux进程

Python 字典的特点和常用操作

一.字典帮助文档 >>> dir(dict) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt

Mysql数据库常用操作

1.备份数据库 [[email protected] ~]# mysqldump -h 192.168.0.8 -uroot  -p'123456'  user >user.sql 2.查看mysql数据库字符集设置 mysql> show variables like 'character_set_%';+--------------------------+----------------------------+| Variable_name            | Value    

Python学习笔记五:字符串常用操作,字典,三级菜单实例

字符串常用操作 7月19日,7月20日 ,7月22日,7月29日,8月29日,2月29日 首字母大写:a_str.capitalize() 统计字符串个数:a_str.count("x") 输出字符,不够的使用指定的字符补上,字符居中:a_str.center(50,"-") 判断字符串以什么结尾:a_str.endwith("xx") 将字符串中的tab转换为指定数目的空格:a_str.expandtabs(tabsize=30) 查找指定字符

MongoDB常用操作

1.MongoDB常用操作 1.1数据库的操作命令 1.创建数据库,使用命令 use 数据库名称 ,如 use sxf. *注意: 1.use 命令后跟的数据库名,如果存在就进入此数据库,如果不存在就创建,所以这种创建方式又叫隐式创建 2.使用命令use sxf创建数据库后,并没有真正生成对应的数据文件,如果此时退出,此数据库将被删除,只有在此数据库中创建集合后,才会真正生成数据文件 2. 删除当前数据库,使用命令 db.dropDatabase() 3.查看所有数据库,使用命令 show db

java:Cookie(常用操作)

 1.常用操作: package cn.zzsxt.lee.web.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.h

TStringList 常用操作

TStringList 常用操作 //TStringList 常用方法与属性: var   List: TStringList;   i: Integer; begin   List := TStringList.Create;   List.Add('Strings1');          {添加}   List.Add('Strings2');   List.Exchange(0,1);            {置换}   List.Insert(0,'Strings3');      {

【Git使用详解】Egit的常用操作详解

常用操作 操作 说明 Fetch 从远程获取最新版本到本地,不会自动merge Merge 可以把一个分支标签或某个commit的修改合并现在的分支上 Pull 从远程获取最新版本并merge到本地相当于fetch+merge Push 将本地分支的更新,推送到远程主机 Merge tool 当你的代码产生了冲突可以通过此工具快速的对比 Switch to 将当前分支切换到其它分支或标签 Commit 将更改提交到本地库中 Rebase 可以把在一个分支里提交的改变移到另一个分支里重放一遍 Re