分类:
C#(13)
版权声明:本文为博主原创文章,未经博主允许不得转载。
一个项目,要做一个从数据库读取数据,然后导出到word,因为涉及到后台数据库的读取,决定用npoi来导出word。
NPOI源码地址:http://npoi.codeplex.com/
NPOI 2.0 api文档: http://www.npoi.info/npoi2tutorial
因为npoi操作word的文章比较少,在由于版本不同,相关的函数可能不一样,这个就需要大家自己去慢慢的探索了。
例如:作者的api文档中
c.字体加粗
r1.SetBold(true);
实际我在调用时,调用的接口是 r1c1.IsBold = 12;
我使用的版本是:NPOI v2.2.0.0
需要引用的命名空间如下
using NPOI.XWPF.UserModel;
using NPOI.OpenXmlFormats.Wordprocessing;
最终效果图如下:
关键代码如下:
- /// <summary>
- /// 新增
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnPrint_Click(object sender, EventArgs e)
- {
- //创建document对象
- XWPFDocument doc = new XWPFDocument();
- //创建段落对象
- XWPFParagraph p1 = doc.CreateParagraph();
- p1.Alignment = ParagraphAlignment.CENTER;//字体居中
- //创建run对象
- //本节提到的所有样式都是基于XWPFRun的,
- //你可以把XWPFRun理解成一小段文字的描述对象,
- //这也是Word文档的特征,即文本描述性文档。
- //来自Tony Qu http://tonyqus.sinaapp.com/archives/609
- XWPFRun runTitle = p1.CreateRun();
- runTitle.IsBold = true;
- runTitle.SetText("军检验收单");
- runTitle.FontSize = 16;
- runTitle.SetFontFamily("宋体", FontCharRange.None);//设置雅黑字体
- XWPFParagraph p2 = doc.CreateParagraph();
- XWPFRun run1 = p2.CreateRun();
- run1.SetText(" 军检项目号:");
- run1.FontSize = 12;
- run1.SetFontFamily("华文楷体", FontCharRange.None);//设置雅黑字体
- #region 头部(6 rows)
- //基本row12,列5;头部6行,4列
- XWPFTable tableTop = doc.CreateTable(6, 5);
- tableTop.Width = 1000 * 5;
- tableTop.SetColumnWidth(0, 1300);/* 设置列宽 */
- tableTop.SetColumnWidth(1, 500);/* 设置列宽 */
- tableTop.SetColumnWidth(2, 1000);/* 设置列宽 */
- tableTop.SetColumnWidth(3, 500);/* 设置列宽 */
- tableTop.SetColumnWidth(4, 1700);/* 设置列宽 */
- tableTop.GetRow(0).MergeCells(1, 4);/* 合并行 */
- tableTop.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "产品名称"));
- tableTop.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " "));
- tableTop.GetRow(1).MergeCells(1, 4);
- tableTop.GetRow(1).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "项目名称"));
- tableTop.GetRow(1).GetCell(1).SetParagraph(SetCellText(doc, tableTop,