网上使用NPOI读取Word文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的。
参考示例:http://www.cnblogs.com/mahongbiao/p/3760878.html
本文使用的NPOI版本是 2.1.1.0,下载地址:http://files.cnblogs.com/files/masonblog/NPOI2.1.1%28.Net2.0%29.zip
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Data; 7 using System.Web.UI.WebControls; 8 using System.IO; 9 using GXEIS.Web.Main.Common; 10 using System.Configuration; 11 using Newtonsoft.Json; 12 using NPOI.XWPF.UserModel; 13 using NPOI.OpenXmlFormats.Wordprocessing; 14 using System.Text; 15 16 namespace CourseMgr 17 { 18 public partial class CourseList : PageBase 19 { 20 21 BLL.Course _CourseBLL = null; 22 Model.v_Course _v_CourseModel = null; 23 BLL.Grade _GradeBLL = null; 24 Model.Grade _GradeModel = null; 25 protected void Page_Load(object sender, EventArgs e) 26 { 27 if (!IsPostBack) 28 { 29 ExportToWordByTemplate(); 30 } 31 } 32 33 #region 根据课程表模板下载Word文档 34 35 /// <summary> 36 /// 根据课程表模板下载Word文档 37 /// </summary> 38 /// <param name="fileName"></param> 39 /// <returns></returns> 40 public void ExportToWordByTemplate() 41 { 42 string sClassName = hfSelectedClass.Value.Trim(); 43 string sYear1 = txtYear1.Text.Trim(); 44 string sYear2 = txtYear2.Text.Trim(); 45 string sSemester = txtSemester.Text.Trim(); 46 string sYear = sYear1 + "-" + sYear2; 47 #region 数据验证 48 if (string.IsNullOrEmpty(sClassName)) 49 { 50 Windows.MessageBox(Page, "请先选择班级", MessageType.Normal); 51 return; 52 } 53 if (string.IsNullOrEmpty(sYear1)) 54 { 55 Windows.MessageBox(Page, "学年不可为空", MessageType.Normal); 56 return; 57 } 58 if (string.IsNullOrEmpty(sYear2)) 59 { 60 Windows.MessageBox(Page, "学年不可为空", MessageType.Normal); 61 return; 62 } 63 if (string.IsNullOrEmpty(sSemester)) 64 { 65 Windows.MessageBox(Page, "学期不可为空", MessageType.Normal); 66 return; 67 } 68 #endregion 69 try 70 { 71 #region 获取课程表数据 72 DataTable dtExport = new DataTable(); 73 BLL.Grade GradeBLL = new BLL.Grade(); 74 Model.Grade GradeModel = GradeBLL.GetModelByGradeClassName(CurrentOperator.OrgNo, sClassName); 75 _CourseBLL = new BLL.Course(); 76 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; 77 #endregion 78 79 #region 打开文档 80 string fileName = Server.MapPath(@"~/Upload/CourseExportTemplate/班级课程表模板.doc"); 81 if (!File.Exists(fileName)) 82 { 83 Windows.MessageBox(Page, "导出失败:课程表模板不存在!", MessageType.Normal); 84 return; 85 } 86 XWPFDocument document = null; 87 using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 88 { 89 document = new XWPFDocument(file); 90 } 91 92 #endregion 93 94 #region 正文段落 95 foreach (XWPFParagraph paragraph in document.Paragraphs) 96 { 97 //判断是否是"**课程表"标题 98 if (paragraph.ParagraphText.Contains("GradeClassName课程表")) 99 { 100 IList<XWPFRun> listRun = paragraph.Runs; 101 while (listRun.Count > 0) 102 { 103 paragraph.RemoveRun(0); 104 } 105 XWPFRun xwpgr1 = paragraph.CreateRun(); 106 xwpgr1.SetBold(true); 107 xwpgr1.FontSize = 23; 108 xwpgr1.SetText(sClassName + "课程表"); 109 xwpgr1.SetTextPosition(30); 110 } 111 } 112 #endregion 113 114 #region 表格 115 int iRow = 0;//表中行的循环索引 116 int iCell = 0;//表中列的循环索引 117 //1.循环Word文档中的表格(该Word模板中就一个课程表) 118 foreach (XWPFTable table in document.Tables) 119 { 120 //2.循环表格行 121 foreach (XWPFTableRow row in table.Rows) 122 { 123 iRow = table.Rows.IndexOf(row);//获取该循环在List集合中的索引 124 //3.循环没行中的列 125 foreach (XWPFTableCell cell in row.GetTableCells()) 126 { 127 iCell = row.GetTableCells().IndexOf(cell);//获取该循环在List集合中的索引 128 //4.进行单元格中内容的获取操作 129 //4.1获取单元格中所有的XWPFParagraph(单元格中每行数据都是一个XWPFParagraph对象) 130 IList<XWPFParagraph> listXWPFParagraph = cell.Paragraphs; 131 //4.1.1如果列中的XWPFParagraph为1个以上则是课程+教师,进行数据操作。 132 if (listXWPFParagraph.Count > 1) 133 { 134 //4.2根据行列获取对应的星期节次的课程信息 135 dvResult.RowFilter = string.Format(" Section='{0}' and WorkingDay='{1}' ", iRow + 1, iCell + 1); 136 //4.2.1获取到对应的课程信息,将单元格中的课程名称和教师名称进行替换 137 if (dvResult.Count > 0) 138 { 139 //第一个XWPFParagraph为课程名称 140 XWPFParagraph xwpfPCource = listXWPFParagraph[0]; 141 if (xwpfPCource != null) 142 { 143 //获取现有的Run集合 144 IList<XWPFRun> listRun = xwpfPCource.Runs; 145 //循环移除 146 while (listRun.Count > 0) 147 { 148 xwpfPCource.RemoveRun(0); 149 } 150 //添加获取的数据 151 XWPFRun xwpgRScience = xwpfPCource.CreateRun(); 152 xwpgRScience.SetText(dvResult[0]["ScienceName"].ToString().Trim()); 153 xwpgRScience.FontSize = 12; 154 xwpfPCource.AddRun(xwpgRScience); 155 } 156 //第二个XWPFParagraph为教师名称 157 XWPFParagraph xwpfPTeacher = listXWPFParagraph[1]; 158 if (xwpfPTeacher != null) 159 { 160 //获取现有的Run集合 161 IList<XWPFRun> listRun = xwpfPTeacher.Runs; 162 //循环移除 163 while (listRun.Count > 0) 164 { 165 xwpfPTeacher.RemoveRun(0); 166 } 167 //添加获取的数据 168 XWPFRun xwpgRTeacher = xwpfPTeacher.CreateRun(); 169 xwpgRTeacher.SetText(dvResult[0]["TeacherName"].ToString().Trim()); 170 xwpgRTeacher.FontSize = 12; 171 xwpfPTeacher.AddRun(xwpgRTeacher); 172 } 173 } 174 //4.2.2没有对应的课程信息。为了美观,移除单元格中的第二个XWPFParagraph,避免出现多个换行符。 175 else 176 { 177 cell.RemoveParagraph(1); 178 } 179 } 180 //4.1.2如果列中的XWPFParagraph为1个则是标题单元格(星期和节次),不进行数据操作。 181 else { } 182 } 183 } 184 } 185 #endregion 186 187 #region 导出文件 188 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 189 document.Write(ms); 190 Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.doc", HttpUtility.UrlEncode(sClassName + "课程表", System.Text.Encoding.UTF8))); 191 Response.BinaryWrite(ms.ToArray()); 192 Response.End(); 193 #endregion 194 } 195 196 catch (Exception ex) 197 { 198 Windows.MessageBox(Page, "导出失败!", MessageType.Normal); 199 LogWrite("导出失败!", ex.ToString(), CurrentOperator.OperatorNo, ResourceID); 200 } 201 } 202 #endregion 203 } 204 }
运行结果:
实例Word文档:http://files.cnblogs.com/files/masonblog/Word%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C.zip