.net core 導出word文檔
Npoi導出word(Peanuts)
標簽: C#npoi導出word合並列列樣式 2015-10-05 22:16 2896人閱讀 評論(0) 收藏 舉報 分類:版權聲明:本文為博主原創文章,未經博主允許不得轉載。
一個項目,要做一個從數據庫讀取數據,然後導出到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;
最終效果圖如下:
關鍵代碼如下:
[csharp] view plain copy
- /// <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, " "));
- tableTop.GetRow(2).MergeCells(1, 4);
- tableTop.GetRow(2).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "施工依據", ParagraphAlignment.CENTER, 45));
- tableTop.GetRow(2).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " ", ParagraphAlignment.CENTER, 45));
- tableTop.GetRow(3).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "檢驗方式"));
- tableTop.GetRow(3).GetCell(1).SetParagraph(SetCellText(doc, tableTop, "獨立檢驗"));
- tableTop.GetRow(3).GetCell(2).SetParagraph(SetCellText(doc, tableTop, " "));
- tableTop.GetRow(3).GetCell(3).SetParagraph(SetCellText(doc, tableTop, "聯合檢驗"));
- tableTop.GetRow(3).GetCell(4).SetParagraph(SetCellText(doc, tableTop, " "));
- tableTop.GetRow(4).MergeCells(3, 4);
- tableTop.GetRow(4).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "設備名稱及編號"));
- tableTop.GetRow(4).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " "));
- tableTop.GetRow(4).GetCell(2).SetParagraph(SetCellText(doc, tableTop, "設備制造廠"));
- tableTop.GetRow(4).GetCell(3).SetParagraph(SetCellText(doc, tableTop, " "));
- //tableTop.GetRow(4).GetCell(3).SetBorderBottom(XWPFtableTop.XWPFBorderType.NONE,0,0,"");
- tableTop.GetRow(5).MergeCells(0, 4);
- CT_P para = new CT_P();
- XWPFParagraph pCell = new XWPFParagraph(para, tableTop.Body);
- pCell.Alignment = ParagraphAlignment.LEFT;//字體居中
- XWPFRun r1c1 = pCell.CreateRun();
- r1c1.SetText("檢驗要素共9項");
- r1c1.FontSize = 12;
- r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
- tableTop.GetRow(5).GetCell(0).SetParagraph(pCell);
- //table.GetRow(6).GetCell(0).SetParagraph(SetCellText(doc, table, "序號"));
- //table.GetRow(6).GetCell(1).SetParagraph(SetCellText(doc, table, "檢驗要素"));
- //table.GetRow(6).GetCell(2).SetParagraph(SetCellText(doc, table, "指標要求"));
- //table.GetRow(6).GetCell(3).SetParagraph(SetCellText(doc, table, "實測值"));
- //table.GetRow(6).GetCell(4).SetParagraph(SetCellText(doc, table, "測量工具編號及有效期"));
- #endregion
- #region 檢驗要素列表部分(數據庫讀取循環顯示)
- /* 打印1頁:小於8行數據,創建9行;
- * 打印2頁:大於8小於26行數據,創建27行。增加18
- * 打印3頁:大於26小於44行數據,創建45行。增加18
- */
- XWPFTable tableContent = doc.CreateTable(45, 5);
- tableContent.Width = 1000 * 5;
- tableContent.SetColumnWidth(0, 300);/* 設置列寬 */
- tableContent.SetColumnWidth(1, 1000);/* 設置列寬 */
- tableContent.SetColumnWidth(2, 1000);/* 設置列寬 */
- tableContent.SetColumnWidth(3, 1000);/* 設置列寬 */
- tableContent.SetColumnWidth(4, 1700);/* 設置列寬 */
- tableContent.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableContent, "序號"));
- tableContent.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableContent, "檢驗要素"));
- tableContent.GetRow(0).GetCell(2).SetParagraph(SetCellText(doc, tableContent, "指標要求"));
- tableContent.GetRow(0).GetCell(3).SetParagraph(SetCellText(doc, tableContent, "實測值"));
- tableContent.GetRow(0).GetCell(4).SetParagraph(SetCellText(doc, tableContent, "測量工具編號及有效期"));
- for (int i = 1; i < 45; i++)
- {
- tableContent.GetRow(i).GetCell(0).SetParagraph(SetCellText(doc, tableContent, i.ToString(), ParagraphAlignment.CENTER, 50));
- tableContent.GetRow(i).GetCell(1).SetParagraph(SetCellText(doc, tableContent, "檢驗要素", ParagraphAlignment.CENTER, 50));
- tableContent.GetRow(i).GetCell(2).SetParagraph(SetCellText(doc, tableContent, "指標要求", ParagraphAlignment.CENTER, 50));
- tableContent.GetRow(i).GetCell(3).SetParagraph(SetCellText(doc, tableContent, "實測值", ParagraphAlignment.CENTER, 50));
- tableContent.GetRow(i).GetCell(4).SetParagraph(SetCellText(doc, tableContent, "測量工具編號及有效期", ParagraphAlignment.CENTER, 50));
- }
- #endregion
- #region 底部內容
- XWPFTable tableBottom = doc.CreateTable(5, 4);
- tableBottom.Width = 1000 * 5;
- tableBottom.SetColumnWidth(0, 1000);/* 設置列寬 */
- tableBottom.SetColumnWidth(1, 1500);/* 設置列寬 */
- tableBottom.SetColumnWidth(2, 1000);/* 設置列寬 */
- tableBottom.SetColumnWidth(3, 1500);/* 設置列寬 */
- tableBottom.GetRow(0).MergeCells(0, 3);/* 合並行 */
- tableBottom.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "附件:", ParagraphAlignment.LEFT, 80));
- tableBottom.GetRow(0).Height = 30;
- tableBottom.GetRow(1).MergeCells(0, 3);/* 合並行 */
- tableBottom.GetRow(1).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "檢驗結論:", ParagraphAlignment.LEFT, 80));
- tableBottom.GetRow(1).Height = 30;
- tableBottom.GetRow(2).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "施工部門"));
- tableBottom.GetRow(2).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
- tableBottom.GetRow(2).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "報驗日期"));
- tableBottom.GetRow(2).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
- tableBottom.GetRow(3).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "軍檢次數"));
- tableBottom.GetRow(3).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
- tableBottom.GetRow(3).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "軍檢日期"));
- tableBottom.GetRow(3).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
- tableBottom.GetRow(4).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "檢驗員"));
- tableBottom.GetRow(4).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
- tableBottom.GetRow(4).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "軍代表"));
- tableBottom.GetRow(4).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
- #endregion
- //保存文件到磁盤WinForm
- //string docPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "DocxWord");
- //if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); }
- //string fileName = string.Format("{0}.doc", HttpUtility.UrlEncode("jjysd" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8));
- //FileStream out1 = new FileStream(Path.Combine(docPath, fileName), FileMode.Create);
- //doc.Write(out1);
- //out1.Close();
- #region 保存導出WebForm
- //Response.Redirect(ResolveUrl(string.Format(@"~\DocxWord\{0}", fileName)));
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- doc.Write(ms);
- Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode("文件名" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8)));
- Response.BinaryWrite(ms.ToArray());
- Response.End();
- ms.Close();
- ms.Dispose();
- //using (MemoryStream ms = new MemoryStream())
- //{
- // doc.Write(ms);
- // Response.ClearContent();
- // Response.Buffer = true;
- // Response.ContentType = "application/octet-stream";
- // Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode("軍檢驗收單" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8)));
- // Response.BinaryWrite(ms.ToArray());
- // //Response.End();
- // Response.Flush();
- // doc = null;
- // ms.Close();
- // ms.Dispose();
- //}
- #endregion
- }
[csharp] view plain copy
- /// <summary>
- /// 設置字體格式
- /// </summary>
- /// <param name="doc"></param>
- /// <param name="table"></param>
- /// <param name="setText"></param>
- /// <returns></returns>
- public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText)
- {
- //table中的文字格式設置
- CT_P para = new CT_P();
- XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
- pCell.Alignment = ParagraphAlignment.CENTER;//字體居中
- pCell.VerticalAlignment = TextAlignment.CENTER;//字體居中
- XWPFRun r1c1 = pCell.CreateRun();
- r1c1.SetText(setText);
- r1c1.FontSize = 12;
- r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
- //r1c1.SetTextPosition(20);//設置高度
- return pCell;
- }
- /// <summary>
- /// 設置單元格格式
- /// </summary>
- /// <param name="doc">doc對象</param>
- /// <param name="table">表格對象</param>
- /// <param name="setText">要填充的文字</param>
- /// <param name="align">文字對齊方式</param>
- /// <param name="textPos">rows行的高度</param>
- /// <returns></returns>
- public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText, ParagraphAlignment align, int textPos)
- {
- CT_P para = new CT_P();
- XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
- //pCell.Alignment = ParagraphAlignment.LEFT;//字體
- pCell.Alignment = align;
- XWPFRun r1c1 = pCell.CreateRun();
- r1c1.SetText(setText);
- r1c1.FontSize = 12;
- r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
- r1c1.SetTextPosition(textPos);//設置高度
- return pCell;
- }
設置table的寬度,以及沒列的寬度代碼如下:
[csharp] view plain copy
- XWPFTable tableTop = doc.CreateTable(6, 5);
- tableTop.Width = 1000 * 5;/* 設置table寬度,必須設置width,SetColumnWidth才有效 */
- 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);/* 合並列 */
XWPFRun r1c1 = pCell.CreateRun();
r1c1.SetText(setText);
r1c1.FontSize = 12;
r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
r1c1.SetTextPosition(textPos);//設置高度
NPOI已出現一段時間了,目前版本2.0 Beta 2 [v2.0.5],網上關於NPOI操作xlsx文章較多,而關於docx的幾乎沒有,盡管NPOI對於Word還不穩定,經過一陣搗鼓後終於實現了表的簡單操作:創建表、創建行、創建單元,單元行和列的合並。
環境:vs2010,netframework4
[csharp] view plain copy print?
- 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 = [email protected]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 = [email protected];
- //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;
- }
- }
.net core 導出word文檔