1. 程式人生 > >.net core 導出word文檔

.net core 導出word文檔

put jsb 數據 沒有 post sha ble 多行 表頭

Npoi導出word(Peanuts)

標簽: C#npoi導出word合並列列樣式 技術分享 分類:

一個項目,要做一個從數據庫讀取數據,然後導出到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
  1. /// <summary>
  2. /// 新增
  3. /// </summary>
  4. /// <param name="sender"></param>
  5. /// <param name="e"></param>
  6. protected void btnPrint_Click(object sender, EventArgs e)
  7. {
  8. //創建document對象
  9. XWPFDocument doc = new XWPFDocument();
  10. //創建段落對象
  11. XWPFParagraph p1 = doc.CreateParagraph();
  12. p1.Alignment = ParagraphAlignment.CENTER;//字體居中
  13. //創建run對象
  14. //本節提到的所有樣式都是基於XWPFRun的,
  15. //你可以把XWPFRun理解成一小段文字的描述對象,
  16. //這也是Word文檔的特征,即文本描述性文檔。
  17. //來自Tony Qu http://tonyqus.sinaapp.com/archives/609
  18. XWPFRun runTitle = p1.CreateRun();
  19. runTitle.IsBold = true;
  20. runTitle.SetText("軍檢驗收單");
  21. runTitle.FontSize = 16;
  22. runTitle.SetFontFamily("宋體", FontCharRange.None);//設置雅黑字體
  23. XWPFParagraph p2 = doc.CreateParagraph();
  24. XWPFRun run1 = p2.CreateRun();
  25. run1.SetText(" 軍檢項目號:");
  26. run1.FontSize = 12;
  27. run1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
  28. #region 頭部(6 rows)
  29. //基本row12,列5;頭部6行,4列
  30. XWPFTable tableTop = doc.CreateTable(6, 5);
  31. tableTop.Width = 1000 * 5;
  32. tableTop.SetColumnWidth(0, 1300);/* 設置列寬 */
  33. tableTop.SetColumnWidth(1, 500);/* 設置列寬 */
  34. tableTop.SetColumnWidth(2, 1000);/* 設置列寬 */
  35. tableTop.SetColumnWidth(3, 500);/* 設置列寬 */
  36. tableTop.SetColumnWidth(4, 1700);/* 設置列寬 */
  37. tableTop.GetRow(0).MergeCells(1, 4);/* 合並行 */
  38. tableTop.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "產品名稱"));
  39. tableTop.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " "));
  40. tableTop.GetRow(1).MergeCells(1, 4);
  41. tableTop.GetRow(1).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "項目名稱"));
  42. tableTop.GetRow(1).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " "));
  43. tableTop.GetRow(2).MergeCells(1, 4);
  44. tableTop.GetRow(2).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "施工依據", ParagraphAlignment.CENTER, 45));
  45. tableTop.GetRow(2).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " ", ParagraphAlignment.CENTER, 45));
  46. tableTop.GetRow(3).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "檢驗方式"));
  47. tableTop.GetRow(3).GetCell(1).SetParagraph(SetCellText(doc, tableTop, "獨立檢驗"));
  48. tableTop.GetRow(3).GetCell(2).SetParagraph(SetCellText(doc, tableTop, " "));
  49. tableTop.GetRow(3).GetCell(3).SetParagraph(SetCellText(doc, tableTop, "聯合檢驗"));
  50. tableTop.GetRow(3).GetCell(4).SetParagraph(SetCellText(doc, tableTop, " "));
  51. tableTop.GetRow(4).MergeCells(3, 4);
  52. tableTop.GetRow(4).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "設備名稱及編號"));
  53. tableTop.GetRow(4).GetCell(1).SetParagraph(SetCellText(doc, tableTop, " "));
  54. tableTop.GetRow(4).GetCell(2).SetParagraph(SetCellText(doc, tableTop, "設備制造廠"));
  55. tableTop.GetRow(4).GetCell(3).SetParagraph(SetCellText(doc, tableTop, " "));
  56. //tableTop.GetRow(4).GetCell(3).SetBorderBottom(XWPFtableTop.XWPFBorderType.NONE,0,0,"");
  57. tableTop.GetRow(5).MergeCells(0, 4);
  58. CT_P para = new CT_P();
  59. XWPFParagraph pCell = new XWPFParagraph(para, tableTop.Body);
  60. pCell.Alignment = ParagraphAlignment.LEFT;//字體居中
  61. XWPFRun r1c1 = pCell.CreateRun();
  62. r1c1.SetText("檢驗要素共9項");
  63. r1c1.FontSize = 12;
  64. r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
  65. tableTop.GetRow(5).GetCell(0).SetParagraph(pCell);
  66. //table.GetRow(6).GetCell(0).SetParagraph(SetCellText(doc, table, "序號"));
  67. //table.GetRow(6).GetCell(1).SetParagraph(SetCellText(doc, table, "檢驗要素"));
  68. //table.GetRow(6).GetCell(2).SetParagraph(SetCellText(doc, table, "指標要求"));
  69. //table.GetRow(6).GetCell(3).SetParagraph(SetCellText(doc, table, "實測值"));
  70. //table.GetRow(6).GetCell(4).SetParagraph(SetCellText(doc, table, "測量工具編號及有效期"));
  71. #endregion
  72. #region 檢驗要素列表部分(數據庫讀取循環顯示)
  73. /* 打印1頁:小於8行數據,創建9行;
  74. * 打印2頁:大於8小於26行數據,創建27行。增加18
  75. * 打印3頁:大於26小於44行數據,創建45行。增加18
  76. */
  77. XWPFTable tableContent = doc.CreateTable(45, 5);
  78. tableContent.Width = 1000 * 5;
  79. tableContent.SetColumnWidth(0, 300);/* 設置列寬 */
  80. tableContent.SetColumnWidth(1, 1000);/* 設置列寬 */
  81. tableContent.SetColumnWidth(2, 1000);/* 設置列寬 */
  82. tableContent.SetColumnWidth(3, 1000);/* 設置列寬 */
  83. tableContent.SetColumnWidth(4, 1700);/* 設置列寬 */
  84. tableContent.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableContent, "序號"));
  85. tableContent.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableContent, "檢驗要素"));
  86. tableContent.GetRow(0).GetCell(2).SetParagraph(SetCellText(doc, tableContent, "指標要求"));
  87. tableContent.GetRow(0).GetCell(3).SetParagraph(SetCellText(doc, tableContent, "實測值"));
  88. tableContent.GetRow(0).GetCell(4).SetParagraph(SetCellText(doc, tableContent, "測量工具編號及有效期"));
  89. for (int i = 1; i < 45; i++)
  90. {
  91. tableContent.GetRow(i).GetCell(0).SetParagraph(SetCellText(doc, tableContent, i.ToString(), ParagraphAlignment.CENTER, 50));
  92. tableContent.GetRow(i).GetCell(1).SetParagraph(SetCellText(doc, tableContent, "檢驗要素", ParagraphAlignment.CENTER, 50));
  93. tableContent.GetRow(i).GetCell(2).SetParagraph(SetCellText(doc, tableContent, "指標要求", ParagraphAlignment.CENTER, 50));
  94. tableContent.GetRow(i).GetCell(3).SetParagraph(SetCellText(doc, tableContent, "實測值", ParagraphAlignment.CENTER, 50));
  95. tableContent.GetRow(i).GetCell(4).SetParagraph(SetCellText(doc, tableContent, "測量工具編號及有效期", ParagraphAlignment.CENTER, 50));
  96. }
  97. #endregion
  98. #region 底部內容
  99. XWPFTable tableBottom = doc.CreateTable(5, 4);
  100. tableBottom.Width = 1000 * 5;
  101. tableBottom.SetColumnWidth(0, 1000);/* 設置列寬 */
  102. tableBottom.SetColumnWidth(1, 1500);/* 設置列寬 */
  103. tableBottom.SetColumnWidth(2, 1000);/* 設置列寬 */
  104. tableBottom.SetColumnWidth(3, 1500);/* 設置列寬 */
  105. tableBottom.GetRow(0).MergeCells(0, 3);/* 合並行 */
  106. tableBottom.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "附件:", ParagraphAlignment.LEFT, 80));
  107. tableBottom.GetRow(0).Height = 30;
  108. tableBottom.GetRow(1).MergeCells(0, 3);/* 合並行 */
  109. tableBottom.GetRow(1).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "檢驗結論:", ParagraphAlignment.LEFT, 80));
  110. tableBottom.GetRow(1).Height = 30;
  111. tableBottom.GetRow(2).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "施工部門"));
  112. tableBottom.GetRow(2).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
  113. tableBottom.GetRow(2).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "報驗日期"));
  114. tableBottom.GetRow(2).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
  115. tableBottom.GetRow(3).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "軍檢次數"));
  116. tableBottom.GetRow(3).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
  117. tableBottom.GetRow(3).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "軍檢日期"));
  118. tableBottom.GetRow(3).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
  119. tableBottom.GetRow(4).GetCell(0).SetParagraph(SetCellText(doc, tableBottom, "檢驗員"));
  120. tableBottom.GetRow(4).GetCell(1).SetParagraph(SetCellText(doc, tableBottom, " "));
  121. tableBottom.GetRow(4).GetCell(2).SetParagraph(SetCellText(doc, tableBottom, "軍代表"));
  122. tableBottom.GetRow(4).GetCell(3).SetParagraph(SetCellText(doc, tableBottom, " "));
  123. #endregion
  124. //保存文件到磁盤WinForm
  125. //string docPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "DocxWord");
  126. //if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); }
  127. //string fileName = string.Format("{0}.doc", HttpUtility.UrlEncode("jjysd" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8));
  128. //FileStream out1 = new FileStream(Path.Combine(docPath, fileName), FileMode.Create);
  129. //doc.Write(out1);
  130. //out1.Close();
  131. #region 保存導出WebForm
  132. //Response.Redirect(ResolveUrl(string.Format(@"~\DocxWord\{0}", fileName)));
  133. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  134. doc.Write(ms);
  135. Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode("文件名" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8)));
  136. Response.BinaryWrite(ms.ToArray());
  137. Response.End();
  138. ms.Close();
  139. ms.Dispose();
  140. //using (MemoryStream ms = new MemoryStream())
  141. //{
  142. // doc.Write(ms);
  143. // Response.ClearContent();
  144. // Response.Buffer = true;
  145. // Response.ContentType = "application/octet-stream";
  146. // Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode("軍檢驗收單" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), System.Text.Encoding.UTF8)));
  147. // Response.BinaryWrite(ms.ToArray());
  148. // //Response.End();
  149. // Response.Flush();
  150. // doc = null;
  151. // ms.Close();
  152. // ms.Dispose();
  153. //}
  154. #endregion
  155. }

[csharp] view plain copy
  1. /// <summary>
  2. /// 設置字體格式
  3. /// </summary>
  4. /// <param name="doc"></param>
  5. /// <param name="table"></param>
  6. /// <param name="setText"></param>
  7. /// <returns></returns>
  8. public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText)
  9. {
  10. //table中的文字格式設置
  11. CT_P para = new CT_P();
  12. XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
  13. pCell.Alignment = ParagraphAlignment.CENTER;//字體居中
  14. pCell.VerticalAlignment = TextAlignment.CENTER;//字體居中
  15. XWPFRun r1c1 = pCell.CreateRun();
  16. r1c1.SetText(setText);
  17. r1c1.FontSize = 12;
  18. r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
  19. //r1c1.SetTextPosition(20);//設置高度
  20. return pCell;
  21. }
  22. /// <summary>
  23. /// 設置單元格格式
  24. /// </summary>
  25. /// <param name="doc">doc對象</param>
  26. /// <param name="table">表格對象</param>
  27. /// <param name="setText">要填充的文字</param>
  28. /// <param name="align">文字對齊方式</param>
  29. /// <param name="textPos">rows行的高度</param>
  30. /// <returns></returns>
  31. public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText, ParagraphAlignment align, int textPos)
  32. {
  33. CT_P para = new CT_P();
  34. XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
  35. //pCell.Alignment = ParagraphAlignment.LEFT;//字體
  36. pCell.Alignment = align;
  37. XWPFRun r1c1 = pCell.CreateRun();
  38. r1c1.SetText(setText);
  39. r1c1.FontSize = 12;
  40. r1c1.SetFontFamily("華文楷體", FontCharRange.None);//設置雅黑字體
  41. r1c1.SetTextPosition(textPos);//設置高度
  42. return pCell;
  43. }


設置table的寬度,以及沒列的寬度代碼如下:

[csharp] view plain copy
  1. XWPFTable tableTop = doc.CreateTable(6, 5);
  2. tableTop.Width = 1000 * 5;/* 設置table寬度,必須設置width,SetColumnWidth才有效 */
  3. tableTop.SetColumnWidth(0, 1300);/* 設置第一列寬 */
  4. tableTop.SetColumnWidth(1, 500);/* 設置第二列寬 */
  5. tableTop.SetColumnWidth(2, 1000);/* 設置列寬 */
  6. tableTop.SetColumnWidth(3, 500);/* 設置列寬 */
  7. 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?
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. MemoryStream ms = new MemoryStream();
  4. XWPFDocument m_Docx = new XWPFDocument();
  5. m_Docx = CreatDocxTable();
  6. m_Docx.Write(ms);
  7. ms.Flush();
  8. SaveToFile(ms,"d:\\test.docx");
  9. }
  10. protected XWPFDocument CreatDocxTable()
  11. {
  12. XWPFDocument m_Docx = new XWPFDocument();
  13. XWPFParagraph p0 = m_Docx.CreateParagraph();
  14. XWPFRun r0 = p0.CreateRun();
  15. r0.SetText("DOCX表");
  16. XWPFTable table = m_Docx.CreateTable(1, 3);//創建一行3列表
  17. table.GetRow(0).GetCell(0).SetText("111");
  18. table.GetRow(0).GetCell(1).SetText("222");
  19. table.GetRow(0).GetCell(2).SetText("333");
  20. XWPFTableRow m_Row = table.CreateRow();//創建一行
  21. m_Row = table.CreateRow();//創建一行
  22. m_Row.GetCell(0).SetText("211");
  23. //合並單元格
  24. m_Row = table.InsertNewTableRow(0);//表頭插入一行
  25. XWPFTableCell cell = m_Row.CreateCell();//創建一個單元格,創建單元格時就創建了一個CT_P
  26. CT_Tc cttc = cell.GetCTTc();
  27. CT_TcPr ctPr = cttc.AddNewTcPr();
  28. ctPr.gridSpan.val = "3";//合並3列
  29. cttc.GetPList()[0].AddNewPPr().AddNewJc().val= ST_Jc.center;
  30. cttc.GetPList()[0].AddNewR().AddNewT().Value = "abc";
  31. XWPFTableRow td3 = table.InsertNewTableRow(table.Rows.Count - 1);//插入行
  32. cell = td3.CreateCell();
  33. cttc = cell.GetCTTc();
  34. ctPr = cttc.AddNewTcPr();
  35. ctPr.gridSpan.val = "3";
  36. cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
  37. cttc.GetPList()[0].AddNewR().AddNewT().Value = "qqq";
  38. //表增加行,合並列
  39. CT_Row m_NewRow = new CT_Row();
  40. m_Row = new XWPFTableRow(m_NewRow, table);
  41. table.AddRow(m_Row); //必須要!!!
  42. cell = m_Row.CreateCell();
  43. cttc = cell.GetCTTc();
  44. ctPr = cttc.AddNewTcPr();
  45. ctPr.gridSpan.val = "3";
  46. cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
  47. cttc.GetPList()[0].AddNewR().AddNewT().Value = "sss";
  48. //表未增加行,合並2列,合並2行
  49. //1行
  50. m_NewRow = new CT_Row();
  51. m_Row = new XWPFTableRow(m_NewRow, table);
  52. table.AddRow(m_Row);
  53. cell = m_Row.CreateCell();
  54. cttc = cell.GetCTTc();
  55. ctPr = cttc.AddNewTcPr();
  56. ctPr.gridSpan.val = "2";
  57. ctPr.AddNewVMerge().val = ST_Merge.restart;//合並行
  58. ctPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直居中
  59. cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
  60. cttc.GetPList()[0].AddNewR().AddNewT().Value = "xxx";
  61. cell = m_Row.CreateCell();
  62. cell.SetText("ddd");
  63. //2行,多行合並類似
  64. m_NewRow = new CT_Row();
  65. m_Row = new XWPFTableRow(m_NewRow, table);
  66. table.AddRow(m_Row);
  67. cell = m_Row.CreateCell();
  68. cttc = cell.GetCTTc();
  69. ctPr = cttc.AddNewTcPr();
  70. ctPr.gridSpan.val = "2";
  71. ctPr.AddNewVMerge().val = [email protected]continue;//合並行
  72. cell = m_Row.CreateCell();
  73. cell.SetText("kkk");
  74. ////3行
  75. //m_NewRow = new CT_Row();
  76. //m_Row = new XWPFTableRow(m_NewRow, table);
  77. //table.AddRow(m_Row);
  78. //cell = m_Row.CreateCell();
  79. //cttc = cell.GetCTTc();
  80. //ctPr = cttc.AddNewTcPr();
  81. //ctPr.gridSpan.val = "2";
  82. //ctPr.AddNewVMerge().val = [email protected];
  83. //cell = m_Row.CreateCell();
  84. //cell.SetText("hhh");
  85. return m_Docx;
  86. }
  87. static void SaveToFile(MemoryStream ms, string fileName)
  88. {
  89. using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  90. {
  91. byte[] data = ms.ToArray();
  92. fs.Write(data, 0, data.Length);
  93. fs.Flush();
  94. data = null;
  95. }
  96. }


技術分享

.net core 導出word文檔