NPOI建立並匯出word

風靈使發表於2018-08-03

WordTest.aspx.cs

using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;

namespace WebDemo
{
    public partial class WordTest : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        ///     新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            //建立document物件
            var doc = new XWPFDocument();

            //建立段落物件1
            var p1 = doc.CreateParagraph();
            p1.Alignment = ParagraphAlignment.CENTER; //字型居中
            //建立run物件
            //本節提到的所有樣式都是基於XWPFRun的,
            //你可以把XWPFRun理解成一小段文字的描述物件,
            //這也是Word文件的特徵,即文字描述性文件。
            //來自Tony Qu http://tonyqus.sinaapp.com/archives/609
            var runTitle = p1.CreateRun();
            runTitle.IsBold = true;
            runTitle.SetText("軍檢驗收單");
            runTitle.FontSize = 16;
            runTitle.SetFontFamily("宋體", FontCharRange.None); //設定雅黑字型

            //建立段落物件2
            var p2 = doc.CreateParagraph();
            var run1 = p2.CreateRun();
            run1.SetText(" 軍檢專案號:");
            run1.FontSize = 12;
            run1.SetFontFamily("華文楷體", FontCharRange.None); //設定雅黑字型

            #region 頭部(6 rows)

            //基本row12,列5;頭部6行,4列
            var 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);
            var para = new CT_P();
            var pCell = new XWPFParagraph(para, tableTop.Body);
            pCell.Alignment = ParagraphAlignment.LEFT; //字型居中

            var 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
                 */
            var 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 (var 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 底部內容

            var 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)));

            var ms = new MemoryStream();
            doc.Write(ms);
            Response.AddHeader("Content-Disposition",
                string.Format("attachment; filename={0}.doc",
                    HttpUtility.UrlEncode("檔名" + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        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
        }

        /// <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中的文字格式設定
            var para = new CT_P();
            var pCell = new XWPFParagraph(para, table.Body);
            pCell.Alignment = ParagraphAlignment.CENTER; //字型居中
            pCell.VerticalAlignment = TextAlignment.CENTER; //字型居中

            var r1c1 = pCell.CreateRun();
            r1c1.SetText(setText);
            r1c1.FontSize = 12;
            r1c1.SetFontFamily("華文楷體", FontCharRange.None); //設定雅黑字型

            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)
        {
            var para = new CT_P();
            var pCell = new XWPFParagraph(para, table.Body);
            //pCell.Alignment = ParagraphAlignment.LEFT;//字型
            pCell.Alignment = align;

            var r1c1 = pCell.CreateRun();
            r1c1.SetText(setText);
            r1c1.FontSize = 12;
            r1c1.SetFontFamily("華文楷體", FontCharRange.None); //設定雅黑字型
            r1c1.SetTextPosition(textPos); //設定高度

            return pCell;
        }
    }
}

執行結果:

這裡寫圖片描述

相關文章