NPOI创建Word
http://www.cnblogs.com/sunbobohu/p/4914999.html
NPOI已出现一段时间了,目前版本2.0 Beta 2 [v2.0.5],网上关于NPOI操作xlsx文章较多,而关于docx的几乎没
有,尽管NPOI对于Word还不稳定,经过一阵捣鼓后终于实现了表的简单操作:创建表、创建行、创建单元,单元行和
列的合并。
环境:vs2010,netframework4
具体代码:
- private void button1_Click(object sender, EventArgs e)
- {
- MemoryStream ms = new MemoryStream();
- XWPFDocument m_Docx = new XWPFDocument();
- m_Docx = CreatDocxTable();
- m_Docx.Write(ms);
- ms.Flush();
- SaveToFile(ms,"d:\\test.docx");
- }
- protected XWPFDocument CreatDocxTable()
- {
- XWPFDocument m_Docx = new XWPFDocument();
- XWPFParagraph p0 = m_Docx.CreateParagraph();
- XWPFRun r0 = p0.CreateRun();
- r0.SetText("DOCX表");
- XWPFTable table = m_Docx.CreateTable(1, 3);//创建一行3列表
- table.GetRow(0).GetCell(0).SetText("111");
- table.GetRow(0).GetCell(1).SetText("222");
- table.GetRow(0).GetCell(2).SetText("333");
- XWPFTableRow m_Row = table.CreateRow();//创建一行
- m_Row = table.CreateRow();//创建一行
- m_Row.GetCell(0).SetText("211");
- //合并单元格
- m_Row = table.InsertNewTableRow(0);//表头插入一行
- XWPFTableCell cell = m_Row.CreateCell();//创建一个单元格,创建单元格时就创建了一个CT_P
- CT_Tc cttc = cell.GetCTTc();
- CT_TcPr ctPr = cttc.AddNewTcPr();
- ctPr.gridSpan.val = "3";//合并3列
- cttc.GetPList()[0].AddNewPPr().AddNewJc().val= ST_Jc.center;
- cttc.GetPList()[0].AddNewR().AddNewT().Value = "abc";
- XWPFTableRow td3 = table.InsertNewTableRow(table.Rows.Count - 1);//插入行
- cell = td3.CreateCell();
- cttc = cell.GetCTTc();
- ctPr = cttc.AddNewTcPr();
- ctPr.gridSpan.val = "3";
- cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
- cttc.GetPList()[0].AddNewR().AddNewT().Value = "qqq";
- //表增加行,合并列
- CT_Row 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.gridSpan.val = "3";
- cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
- cttc.GetPList()[0].AddNewR().AddNewT().Value = "sss";
- //表未增加行,合并2列,合并2行
- //1行
- 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.gridSpan.val = "2";
- 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";
- cell = m_Row.CreateCell();
- cell.SetText("ddd");
- //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.gridSpan.val = "2";
- ctPr.AddNewVMerge().val = ST_Merge.@continue;//合并行
- cell = m_Row.CreateCell();
- cell.SetText("kkk");
- ////3行
- //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.gridSpan.val = "2";
- //ctPr.AddNewVMerge().val = ST_Merge.@continue;
- //cell = m_Row.CreateCell();
- //cell.SetText("hhh");
- return m_Docx;
- }
- static void SaveToFile(MemoryStream ms, string fileName)
- {
- using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
- {
- byte[] data = ms.ToArray();
- fs.Write(data, 0, data.Length);
- fs.Flush();
- data = null;
- }
- }
上面代码所创建的表见图
========
NPOI 2.0导出word(docx格式)
http://www.tuicool.com/articles/JFZzUj
主题 NPOI
大名鼎鼎的NPOI用来导出EXCEL的文章园子里面有很多,可是用来导出WORD文档的文章大都含糊不清,最近刚好完
成一个导出WORD文档的需求,在此分享下。
NPOI里面认为word文档的最基本的结构是段落,代表这个段落的类就是 XWPFParagraph ,使用这个类可以设置段落
里面的字体、大小、以及是否加粗等。
代表整个文档的的类 XWPFDocument ,是最外层的容器相当于一个word文档的实例,代表表格的类 XWPFTable ,
是较小级别的段落容器相当于一个表格的实例。
一个 XWPFDocument 可以添加多个 XWPFTable 和多个 XWPFParagraph ,一个 XWPFTable 可以添加多个
XWPFParagraph
现在我们要创建一个有几个段落和表格的word文档,其中,表格里面要显示带格式的文字(微软雅黑,小四),形如
首先,需要创建一个 XWPFDocument doc = new XWPFDocument (),随后用文档实例doc创建段落1~段落n
- XWPFParagraph p0 = doc.CreateParagraph();
- p0.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r0 = p0.CreateRun();
- r0.SetFontFamily("宋体");
- r0.SetFontSize(18);
- r0.SetBold(true);
- r0.SetText("未登录过学生的账号密码");
- XWPFParagraph p1 = doc.CreateParagraph();
- p1.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r1 = p1.CreateRun();
- r1.SetFontFamily("宋体");
- r1.SetFontSize(10);
- r1.SetBold(true);
- r1.SetText("(备注:已登录过的学生密码不显示)");
- XWPFParagraph p2 = doc.CreateParagraph();
- p2.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r2 = p2.CreateRun();
- r2.SetFontFamily("宋体");
- r2.SetFontSize(10);
- r2.SetBold(true);
- r2.SetText("学校:XX一中");
- XWPFParagraph p3 = doc.CreateParagraph();
- p3.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r3 = p3.CreateRun();
- r3.SetFontFamily("宋体");
- r3.SetFontSize(10);
- r3.SetBold(true);
- r3.SetText("班级:(7)");
- XWPFParagraph p4 = doc.CreateParagraph();
- p4.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r4 = p4.CreateRun();
- r4.SetFontFamily("宋体");
- r4.SetFontSize(10);
- r4.SetBold(true);
- r4.SetText("班主任:ddd");
- XWPFParagraph p5 = doc.CreateParagraph();
- p5.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r5 = p5.CreateRun();
- r5.SetFontFamily("宋体");
- r5.SetFontSize(10);
- r5.SetBold(true);
- r5.SetText("可以在此处添加备注:");
然后用doc创建个4行4列 XWPFTable table = doc.CreateTable(4, 4)
接着很多人根据vs的点出来的方法或者是NPOI原作者tonyqus的教程 http://tonyqus.sinaapp.com/archives/614 ,使
用table的单元格的SetParagraph()方法直接设置构造好的段落就行了, 但是,事实证明这样做是不对的,这样的话会
使得构造出来的段落不光会显示在table里面,而且还会显示在其他地方。正确的方法应该是使用table单元格的
AddParagraph()方法直接生成一个专属于表格的段落。
- XWPFParagraph pIO = table.GetRow(i).GetCell(0).AddParagraph();
- XWPFRun rIO = pIO.CreateRun();
- rIO.SetFontFamily("微软雅黑");
- rIO.SetFontSize(12);
- rIO.SetBold(true);
- rIO.SetText(i.ToString());
- XWPFParagraph pINo =table.GetRow(i).GetCell(1).AddParagraph();
- XWPFRun rINo = pINo.CreateRun();
- rINo.SetFontFamily("微软雅黑");
- rINo.SetFontSize(12);
- rINo.SetBold(true);
- rINo.SetText(notLoginStudents[i - 1].UserName);15
- XWPFParagraph pIMm = table.GetRow(i).GetCell(2).AddParagraph();
- XWPFRun rIMm = pIMm.CreateRun();
- rIMm.SetFontFamily("微软雅黑");
- rIMm.SetFontSize(12);
- rIMm.SetBold(true);
- rIMm.SetText(notLoginStudents[i - 1].PassWord);23
- XWPFParagraph pIName = table.GetRow(i).GetCell(3).AddParagraph();
- XWPFRun rIName = pIName.CreateRun();
- rIName.SetFontFamily("微软雅黑");
- rIName.SetFontSize(12);
- rIName.SetBold(true);
- rIName.SetText(notLoginStudents[i - 1].StudentName);
随后,把文档写入流doc.Write(new MemoryStream()),接着你想干神马就都OK了。
========
NPOI创建DOCX常用操作
http://blog.csdn.net/gltide/article/details/39929259
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。例中提供了创建表、插图和图表实现的代码。
========
使用NOPI读取Word、Excel文档内容
http://www.cnblogs.com/mahongbiao/p/3760878.html
使用NOPI读取Excel的例子很多,读取Word的例子不多。
Excel的解析方式有多中,可以使用ODBC查询,把Excel作为一个数据集对待。也可以使用文档结构模型的方式进行解析
,即解析Workbook(工作簿)、Sheet、Row、Column。
Word的解析比较复杂,因为Word的文档结构模型定义较为复杂。解析Word或者Excel,关键是理解Word、Excel的文
档对象模型。
Word、Excel文档对象模型的解析,可以通过COM接口调用,此类方式使用较广。(可以录制宏代码,然后替换为对应
的语言)
也可以使用XML模型解析,尤其是对于2007、2010版本的文档的解析。
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
namespace eyuan
{
public static class NOPIHandler
{
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<List<List<string>>> ReadExcel(string fileName)
{
//打开Excel工作簿
XSSFWorkbook hssfworkbook = null;
try
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new XSSFWorkbook(file);
}
}
catch (Exception e)
{
LogHandler.LogWrite(string.Format("文件{0}打开失败,错误:{1}", new string[] { fileName,
e.ToString() }));
}
//循环Sheet页
int sheetsCount = hssfworkbook.NumberOfSheets;
List<List<List<string>>> workBookContent = new List<List<List<string>>>();
for (int i = 0; i < sheetsCount; i++)
{
//Sheet索引从0开始
ISheet sheet = hssfworkbook.GetSheetAt(i);
//循环行
List<List<string>> sheetContent = new List<List<string>>();
int rowCount = sheet.PhysicalNumberOfRows;
for (int j = 0; j < rowCount; j++)
{
//Row(逻辑行)的索引从0开始
IRow row = sheet.GetRow(j);
//循环列(各行的列数可能不同)
List<string> rowContent = new List<string>();
int cellCount = row.PhysicalNumberOfCells;
for (int k = 0; k < cellCount; k++)
{
//ICell cell = row.GetCell(k);
ICell cell = row.Cells[k];
if (cell == null)
{
rowContent.Add("NIL");
}
else
{
rowContent.Add(cell.ToString());
//rowContent.Add(cell.StringCellValue);
}
}
//添加行到集合中
sheetContent.Add(rowContent);
}
//添加Sheet到集合中
workBookContent.Add(sheetContent);
}
return workBookContent;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ReadExcelText(string fileName)
{
string ExcelCellSeparator = ConfigurationManager.AppSettings["ExcelCellSeparator"];
string ExcelRowSeparator = ConfigurationManager.AppSettings["ExcelRowSeparator"];
string ExcelSheetSeparator = ConfigurationManager.AppSettings["ExcelSheetSeparator"];
//
List<List<List<string>>> excelContent = ReadExcel(fileName);
string fileText = string.Empty;
StringBuilder sbFileText = new StringBuilder();
//循环处理WorkBook中的各Sheet页
List<List<List<string>>>.Enumerator enumeratorWorkBook = excelContent.GetEnumerator();
while (enumeratorWorkBook.MoveNext())
{
//循环处理当期Sheet页中的各行
List<List<string>>.Enumerator enumeratorSheet =
enumeratorWorkBook.Current.GetEnumerator();
while (enumeratorSheet.MoveNext())
{
string[] rowContent = enumeratorSheet.Current.ToArray();
sbFileText.Append(string.Join(ExcelCellSeparator, rowContent));
sbFileText.Append(ExcelRowSeparator);
}
sbFileText.Append(ExcelSheetSeparator);
}
//
fileText = sbFileText.ToString();
return fileText;
}
/// <summary>
/// 读取Word内容
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ReadWordText(string fileName)
{
string WordTableCellSeparator = ConfigurationManager.AppSettings["WordTableCellSeparator"];
string WordTableRowSeparator = ConfigurationManager.AppSettings["WordTableRowSeparator"];
string WordTableSeparator = ConfigurationManager.AppSettings["WordTableSeparator"];
//
string CaptureWordHeader = ConfigurationManager.AppSettings["CaptureWordHeader"];
string CaptureWordFooter = ConfigurationManager.AppSettings["CaptureWordFooter"];
string CaptureWordTable = ConfigurationManager.AppSettings["CaptureWordTable"];
string CaptureWordImage = ConfigurationManager.AppSettings["CaptureWordImage"];
//
string CaptureWordImageFileName = ConfigurationManager.AppSettings
["CaptureWordImageFileName"];
//
string fileText = string.Empty;
StringBuilder sbFileText = new StringBuilder();
#region 打开文档
XWPFDocument document = null;
try
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
document = new XWPFDocument(file);
}
}
catch (Exception e)
{
LogHandler.LogWrite(string.Format("文件{0}打开失败,错误:{1}", new string[] { fileName,
e.ToString() }));
}
#endregion
#region 页眉、页脚
//页眉
if (CaptureWordHeader == "true")
{
sbFileText.AppendLine("Capture Header Begin");
foreach (XWPFHeader xwpfHeader in document.HeaderList)
{
sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfHeader.Text }));
}
sbFileText.AppendLine("Capture Header End");
}
//页脚
if (CaptureWordFooter == "true")
{
sbFileText.AppendLine("Capture Footer Begin");
foreach (XWPFFooter xwpfFooter in document.FooterList)
{
sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfFooter.Text }));
}
sbFileText.AppendLine("Capture Footer End");
}
#endregion
#region 表格
if (CaptureWordTable == "true")
{
sbFileText.AppendLine("Capture Table Begin");
foreach (XWPFTable table in document.Tables)
{
//循环表格行
foreach (XWPFTableRow row in table.Rows)
{
foreach (XWPFTableCell cell in row.GetTableCells())
{
sbFileText.Append(cell.GetText());
//
sbFileText.Append(WordTableCellSeparator);
}
sbFileText.Append(WordTableRowSeparator);
}
sbFileText.Append(WordTableSeparator);
}
sbFileText.AppendLine("Capture Table End");
}
#endregion
#region 图片
if (CaptureWordImage == "true")
{
sbFileText.AppendLine("Capture Image Begin");
foreach (XWPFPictureData pictureData in document.AllPictures)
{
string picExtName = pictureData.suggestFileExtension();
string picFileName = pictureData.GetFileName();
byte[] picFileContent = pictureData.GetData();
//
string picTempName = string.Format(CaptureWordImageFileName, new string[] {
Guid.NewGuid().ToString() + "_" + picFileName + "." + picExtName });
//
using (FileStream fs = new FileStream(picTempName, FileMode.Create, FileAccess.Write))
{
fs.Write(picFileContent, 0, picFileContent.Length);
fs.Close();
}
//
sbFileText.AppendLine(picTempName);
}
sbFileText.AppendLine("Capture Image End");
}
#endregion
//正文段落
sbFileText.AppendLine("Capture Paragraph Begin");
foreach (XWPFParagraph paragraph in document.Paragraphs)
{
sbFileText.AppendLine(paragraph.ParagraphText);
}
sbFileText.AppendLine("Capture Paragraph End");
//
//
fileText = sbFileText.ToString();
return fileText;
}
}
}
========
C# WebForm 使用NPOI 2 生成简单的word文档(.docx)
http://doc.okbase.net/LFDX/archive/98909.html
使用NPOI可以方便的实现服务端对Word、Excel的读写。要实现对Word的读写操作,需要引用NPOI.OOXML.dll,应用命名空间XWPF。
本文使用NPOI 2.0实现对Word的基本生成、下载操作。 NOPI 2.0 下载地址:http://npoi.codeplex.com/downloads/get/764162
虽然现在最新版本为NPOI 2.1.1 ,但笔者使用2.1.1的NPOI.OOXML.dll时,发现无法实现段落格式化功能,故推荐使用本文版本。
需要添加的命名空间:
- using System.IO;
- using NPOI.XWPF.UserModel;
- XWPFDocument doc = new XWPFDocument(); //创建新的word文档
- XWPFParagraph p1 = doc.CreateParagraph(); //向新文档中添加段落
- p1.SetAlignment(ParagraphAlignment.CENTER); //段落对其方式为居中
- XWPFRun r1 = p1.CreateRun(); //向该段落中添加文字
- r1.SetText("测试段落一");
- XWPFParagraph p2 = doc.CreateParagraph();
- p2.SetAlignment(ParagraphAlignment.LEFT);
- XWPFRun r2 = p2.CreateRun();
- r2.SetText("测试段落二");
- FileStream sw = File.Create("cutput.docx"); //...
- doc.Write(sw); //...
- sw.Close(); //在服务端生成文件
- FileInfo file = new FileInfo("cutput.docx");//文件保存路径及名称
- //注意: 文件保存的父文件夹需添加Everyone用户,并给予其完全控制权限
- Response.Clear();
- Response.ClearHeaders();
- Response.Buffer = false;
- Response.ContentType = "application/octet-stream";
- Response.AppendHeader("Content-Disposition", "attachment;filename="
- + HttpUtility.UrlEncode("output.docx", System.Text.Encoding.UTF8));
- Response.AppendHeader("Content-Length", file.Length.ToString());
- Response.WriteFile(file.FullName);
- Response.Flush(); //以上将生成的word文件发送至用户浏览器
- File.Delete("cutput.docx"); //清除服务端生成的word文件
========