.Net Core NOPI操作word(一)
NOPI使用方式
1.安装nuget包 即可使用
Install-Package NPOI
一、创建word文档
//创建生成word文档 string path = "D:\\test.docx"; XWPFDocument doc = new XWPFDocument(); // 添加段落 XWPFParagraph gp = doc.CreateParagraph(); gp.Alignment = ParagraphAlignment.CENTER;//水平居中 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("NPOI创建Word2007Docx"); gp = doc.CreateParagraph(); gr = gp.CreateRun(); CT_RPr rpr = gr.GetCTR().AddNewRPr(); CT_Fonts rfonts = rpr.AddNewRFonts(); rfonts.ascii = "宋体"; rfonts.eastAsia = "宋体"; rpr.AddNewSz().val = (ulong)21;//5号字体 rpr.AddNewSzCs().val = (ulong)21; gr.SetText("NPOI,顾名思义,就是POI的.NET版本。那POI又是什么呢?POI是一套用Java写成的库,能够帮助开 发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等 。目前POI的稳定版本中支持Excel文件格式(xls和xlsx),其他的都属于不稳定版本(放在poi的scrachpad目录 中)。"); gp = doc.CreateParagraph(); //添加表格 XWPFTable table = doc.CreateTable(1, 4);//创建一行4列表 CT_Tbl m_CTTbl = doc.Document.body.GetTblArray()[0];//获得文档第一张表 CT_TblPr m_CTTblPr = m_CTTbl.AddNewTblPr(); m_CTTblPr.AddNewTblW().w = "2000"; //表宽 m_CTTblPr.AddNewTblW().type = ST_TblWidth.dxa; m_CTTblPr.tblpPr = new CT_TblPPr();//表定位 m_CTTblPr.tblpPr.tblpX = "4003";//表左上角坐标 m_CTTblPr.tblpPr.tblpY = "365"; m_CTTblPr.tblpPr.tblpXSpec = ST_XAlign.center;//若不为“Null”,则优先tblpX,即表由tblpXSpec定位 m_CTTblPr.tblpPr.tblpYSpec = ST_YAlign.center;//若不为“Null”,则优先tblpY,即表由tblpYSpec定位 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; //表1行4列充值:a,b,c,d table.GetRow(0).GetCell(0).SetText("a"); table.GetRow(0).GetCell(1).SetText("b"); table.GetRow(0).GetCell(2).SetText("c"); table.GetRow(0).GetCell(3).SetText("d"); CT_Row m_NewRow = new CT_Row();//创建1行 XWPFTableRow m_Row = new XWPFTableRow(m_NewRow, table); table.AddRow(m_Row); //必须要!!! 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 = "666"; cell = m_Row.CreateCell();//创建单元格,也创建了一个CT_P cell.GetCTTc().GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center; cell.GetCTTc().GetPList()[0].AddNewR().AddNewT().Value = "e"; using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { doc.Write(fs); Console.WriteLine("生成word成功"); }
生成word内容如下:
更多参考:
https://blog.csdn.net/qq_35534449/article/details/79205468
https://blog.csdn.net/qq_32109957/article/details/86577938