使用NPOI读取Word文档内容并进行修改
阅读原文时间:2021年08月25日阅读:2

网上使用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  
}  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章