使用NPOI将数据导出为word格式里的table

开发环境:VS2013+MySQL5.5+EF6+NPOI2.0.6

格式:WinForm+CodeFirst

PS:vs2013的CodeFirst很方便了啊

CodeFirst方式就不再赘述了。

此Demo托管地址:http://git.oschina.net/uustudy/ExportImportWord.git

另外推荐下NPOI代码托管地址:https://github.com/tonyqus/npoi

作者博客:http://tonyqus.sinaapp.com/

使用nuget安装NPOI:

Install-Package NPOI

然后就来看看这些代码

private void btnExport_Click(object sender, EventArgs e)
        {
            var dbcontext = new BlogModel();
            var list = dbcontext.ArticleInfos.ToList();
            //创建document对象
            XWPFDocument doc = new XWPFDocument();
            //创建段落对象
            XWPFParagraph p1 = doc.CreateParagraph();
            //创建run对象
            //本节提到的所有样式都是基于XWPFRun的,
            //你可以把XWPFRun理解成一小段文字的描述对象,
            //这也是Word文档的特征,即文本描述性文档。
            //来自Tony Qu http://tonyqus.sinaapp.com/archives/609
            XWPFRun r1 = p1.CreateRun();
            r1.SetBold(true);
            r1.SetText("数据导出demo");
            r1.SetBold(true);
            r1.SetFontFamily("Arial");//设置雅黑字体
            //创建表格对象列数写死了,可根据自己需要改进或者自己想想解决方案
            XWPFTable table = doc.CreateTable(list.Count(), 4);
            for (int i = 0; i < list.Count(); i++)
            {
                table.GetRow(i).GetCell(0).SetText(list[i].Id.ToString());
                table.GetRow(i).GetCell(1).SetText(list[i].Title);
                table.GetRow(i).GetCell(2).SetText(list[i].Content);
                table.GetRow(i).GetCell(3).SetText(list[i].AddTime);
            }
            //保存文件到磁盘
            FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create);
            doc.Write(out1);
            out1.Close();
        }

代码上写的有较为详细的注释,有需要的朋友可以自己试试

 

posted @ 2014-05-20 22:27  逆水寒龙  阅读(15313)  评论(5编辑  收藏  举报