開發環境: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();
}
代碼上寫的有較為詳細的注釋,有需要的朋友可以自己試試
