Npoi導出word(Peanuts)


          一個項目,要做一個從數據庫讀取數據,然後導出到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;

        

        最終效果圖如下:

     

     關鍵代碼如下:

     

  /// <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
    }

    /// <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的寬度,以及沒列的寬度代碼如下:

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);//設置高度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章