使用NPOI讀取Word文檔內容並進行修改


前言

網上使用NPOI讀取Word文件的例子現在也不少,本文就是參考網上大神們的例子進行修改以適應自己需求的。

參考博文

http://www.cnblogs.com/mahongbiao/p/3760878.html

本文使用的NPOI版本是 2.1.1.0(.net2.0)  下載鏈接  https://files.cnblogs.com/files/masonblog/NPOI2-1-1DotNet2-0.zip

本例Word文檔  https://files.cnblogs.com/files/masonblog/NPOIWordTestRun.zip

運行結果

 

 

 

示例代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using GXEIS.Web.Main.Common;
using System.Configuration;
using Newtonsoft.Json;
using NPOI.XWPF.UserModel;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Text;

namespace CourseMgr
{
    public partial class CourseList : PageBase
    {

        BLL.Course _CourseBLL = null;
        Model.v_Course _v_CourseModel = null;
        BLL.Grade _GradeBLL = null;
        Model.Grade _GradeModel = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ExportToWordByTemplate();
            }
        }
           
        #region 根據課程表模板下載Word文檔

        /// <summary>
        /// 根據課程表模板下載Word文檔
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public void ExportToWordByTemplate()
        {
            string sClassName = hfSelectedClass.Value.Trim();
            string sYear1 = txtYear1.Text.Trim();
            string sYear2 = txtYear2.Text.Trim();
            string sSemester = txtSemester.Text.Trim();
            string sYear = sYear1 + "-" + sYear2;
            #region 數據驗證
            if (string.IsNullOrEmpty(sClassName))
            {
                Windows.MessageBox(Page, "請先選擇班級", MessageType.Normal);
                return;
            }
            if (string.IsNullOrEmpty(sYear1))
            {
                Windows.MessageBox(Page, "學年不可為空", MessageType.Normal);
                return;
            }
            if (string.IsNullOrEmpty(sYear2))
            {
                Windows.MessageBox(Page, "學年不可為空", MessageType.Normal);
                return;
            }
            if (string.IsNullOrEmpty(sSemester))
            {
                Windows.MessageBox(Page, "學期不可為空", MessageType.Normal);
                return;
            }
            #endregion
            try
            {
                #region 獲取課程表數據
                DataTable dtExport = new DataTable();
                BLL.Grade GradeBLL = new BLL.Grade();
                Model.Grade GradeModel = GradeBLL.GetModelByGradeClassName(CurrentOperator.OrgNo, sClassName);
                _CourseBLL = new BLL.Course();
                DataView dvResult = _CourseBLL.GetViewList(string.Format("OrgNo='{0}' and YearStr='{1}' and Semester='{2}' and ClassNo='{3}' ", CurrentOperator.OrgNo, sYear, sSemester, GradeModel.GradeNo)).Tables[0].DefaultView;
                #endregion

                #region 打開文檔
                string fileName = Server.MapPath(@"~/Upload/CourseExportTemplate/班級課程表模板.doc");
                if (!File.Exists(fileName))
                {
                    Windows.MessageBox(Page, "導出失敗:課程表模板不存在!", MessageType.Normal);
                    return;
                }
                XWPFDocument document = null;
                using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    document = new XWPFDocument(file);
                }

                #endregion

                #region 正文段落
                foreach (XWPFParagraph paragraph in document.Paragraphs)
                {
                    //判斷是否是"**課程表"標題
                    if (paragraph.ParagraphText.Contains("GradeClassName課程表"))
                    {
                        IList<XWPFRun> listRun = paragraph.Runs;
                        while (listRun.Count > 0)
                        {
                            paragraph.RemoveRun(0);
                        }
                        XWPFRun xwpgr1 = paragraph.CreateRun();
                        xwpgr1.SetBold(true);
                        xwpgr1.FontSize = 23;
                        xwpgr1.SetText(sClassName + "課程表");
                        xwpgr1.SetTextPosition(30);
                    }
                }
                #endregion

                #region 表格
                int iRow = 0;//表中行的循環索引
                int iCell = 0;//表中列的循環索引
                //1.循環Word文檔中的表格(該Word模板中就一個課程表)
                foreach (XWPFTable table in document.Tables)
                {
                    //2.循環表格行
                    foreach (XWPFTableRow row in table.Rows)
                    {
                        iRow = table.Rows.IndexOf(row);//獲取該循環在List集合中的索引
                        //3.循環沒行中的列
                        foreach (XWPFTableCell cell in row.GetTableCells())
                        {
                            iCell = row.GetTableCells().IndexOf(cell);//獲取該循環在List集合中的索引
                            //4.進行單元格中內容的獲取操作
                            //4.1獲取單元格中所有的XWPFParagraph(單元格中每行數據都是一個XWPFParagraph對象)
                            IList<XWPFParagraph> listXWPFParagraph = cell.Paragraphs;
                            //4.1.1如果列中的XWPFParagraph為1個以上則是課程+教師,進行數據操作。                            
                            if (listXWPFParagraph.Count > 1)
                            {
                                //4.2根據行列獲取對應的星期節次的課程信息
                                dvResult.RowFilter = string.Format(" Section='{0}' and WorkingDay='{1}' ", iRow + 1, iCell + 1);
                                //4.2.1獲取到對應的課程信息,將單元格中的課程名稱和教師名稱進行替換
                                if (dvResult.Count > 0)
                                {
                                    //第一個XWPFParagraph為課程名稱
                                    XWPFParagraph xwpfPCource = listXWPFParagraph[0];
                                    if (xwpfPCource != null)
                                    {
                                        //獲取現有的Run集合
                                        IList<XWPFRun> listRun = xwpfPCource.Runs;
                                        //循環移除
                                        while (listRun.Count > 0)
                                        {
                                            xwpfPCource.RemoveRun(0);
                                        }
                                        //添加獲取的數據
                                        XWPFRun xwpgRScience = xwpfPCource.CreateRun();
                                        xwpgRScience.SetText(dvResult[0]["ScienceName"].ToString().Trim());
                                        xwpgRScience.FontSize = 12;
                                        xwpfPCource.AddRun(xwpgRScience);
                                    }
                                    //第二個XWPFParagraph為教師名稱
                                    XWPFParagraph xwpfPTeacher = listXWPFParagraph[1];
                                    if (xwpfPTeacher != null)
                                    {
                                        //獲取現有的Run集合
                                        IList<XWPFRun> listRun = xwpfPTeacher.Runs;
                                        //循環移除
                                        while (listRun.Count > 0)
                                        {
                                            xwpfPTeacher.RemoveRun(0);
                                        }
                                        //添加獲取的數據
                                        XWPFRun xwpgRTeacher = xwpfPTeacher.CreateRun();
                                        xwpgRTeacher.SetText(dvResult[0]["TeacherName"].ToString().Trim());
                                        xwpgRTeacher.FontSize = 12;
                                        xwpfPTeacher.AddRun(xwpgRTeacher);
                                    }
                                }
                                //4.2.2沒有對應的課程信息。為了美觀,移除單元格中的第二個XWPFParagraph,避免出現多個換行符。
                                else
                                {
                                    cell.RemoveParagraph(1);
                                }
                            }
                            //4.1.2如果列中的XWPFParagraph為1個則是標題單元格(星期和節次),不進行數據操作。
                            else { }
                        }
                    }
                }
                #endregion

                #region 導出文件
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                document.Write(ms);
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode(sClassName + "課程表", System.Text.Encoding.UTF8)));
                Response.BinaryWrite(ms.ToArray());
                Response.End();
                #endregion
            }

            catch (Exception ex)
            {
                Windows.MessageBox(Page, "導出失敗!", MessageType.Normal);
                LogWrite("導出失敗!", ex.ToString(), CurrentOperator.OperatorNo, ResourceID);
            }
        }
        #endregion
    }
}    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM