首页 > 其他分享 >npoi读取word 内容控件

npoi读取word 内容控件

时间:2024-10-26 15:58:04浏览次数:5  
标签:控件 arr word ++ Items npoi var null CT

void Main()
{
	//打开word文件
	XWPFDocument document = null;
	try
	{
		using (FileStream stream = File.OpenRead(@"15.docx"))
		{
			document = new XWPFDocument(stream);
		}
		CT_Body body = document.Document.body;

		var controls = body.getValueFromContentControl();
		for (int i = 0; i < controls.Count; i++)
		{
			Console.WriteLine(controls[i].Title);
			Console.WriteLine(controls[i].Tip);
			Console.WriteLine(controls[i].Text);
			Console.WriteLine("_____________________");
		}

		//设置内容控件的值
		body.SetValueToContentControl("title1 ", "标题1");

		//替换标签内容
		body.SetValueToBookmark("bookmark1", "");

		//保存文件
		string filename = Path.Combine(@"15.docx");
		using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
		{
			document.Write(fs);
			document.Close();
		}
		//打开文件夹
		System.Diagnostics.Process.Start("explorer.exe", Path.Combine(@"15.docx"));

	}
	catch (Exception ex)
	{
		throw new Exception(string.Format("文件{0}打开失败,错误:{1}", new string[] { "", ex.ToString() }));
	}
}

public static class NPOI_Word
{
	/// <summary>获取word的内容控件的值</summary>
	public static List<ContentControl> getValueFromContentControl(this CT_Body body)
	{
		var controls = new List<ContentControl>();
		getValueFromContentControl1(body.Items, controls);
		return controls;
	}
	private static void getValueFromContentControl1(ArrayList items, List<ContentControl> controls)
	{

		for (int i = 0; i < items.Count; i++)
		{
			var item = items[i];
			if (item.GetType() == typeof(CT_P))
			{
				var p = item as CT_P;
				var arr = p.Items;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j];
					if (a.GetType() == typeof(CT_SdtRun))
					{
						CT_SdtRun sdt = a as CT_SdtRun;
						var list = sdt.sdtPr.Items;

						string title = "";
						string text = "";
						var tag = "";
						for (int k = 0; k < list.Count; k++)
						{
							var b = list[k];
							if (b.GetType() == typeof(CT_String) && k == 1)
							{
								title = (b as CT_String).val;
							}
							if (b.GetType() == typeof(CT_String) && k == 2)
							{
								tag = (b as CT_String).val;
							}
						}
						var a1 = sdt.sdtContent.Items[0];
						if (a1 is CT_R)
						{
							var text1 = (a1 as CT_R).Items[0];
							text = (text1 as CT_Text).Value;
						}
						controls.Add(new ContentControl() { Title = title, Tip = tag, Text = text });
					}
				}
			}
			else if (item.GetType() == typeof(CT_Tbl))
			{
				CT_Tbl tbl = item as CT_Tbl;
				ArrayList arr = tbl.Items1;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j] as CT_Row;
					if (a != null)
					{
						var cells = a.Items;

						for (int k = 0; k < cells.Count; k++)
						{
							var cell = cells[k] as CT_Tc;
							if (cell != null)
							{
								var c_ps = cell.Items;
								for (int h = 0; h < c_ps.Count; h++)
								{
									var c_p = c_ps[h] as CT_P;
									if (c_p != null)
									{
										getValueFromContentControl1(c_ps, controls);
									}
								}
							}
						}
					}
				}
			}
		}
	}

	/// <summary>
	/// 给word的内容控件赋值
	/// </summary>
	/// <param name="body"></param>
	/// <param name="title">控件的标题</param>
	/// <param name="value">要赋的值</param>
	/// <returns></returns>
	public static void SetValueToContentControl(this CT_Body body, string title, string value)
	{
		setValueToContentControl1(body.Items, title, value);
	}
	private static void setValueToContentControl1(ArrayList items, string title, string text)
	{
		for (int i = 0; i < items.Count; i++)
		{
			var item = items[i];
			if (item.GetType() == typeof(CT_P))
			{
				var p = item as CT_P;
				var arr = p.Items;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j];
					if (a.GetType() == typeof(CT_SdtRun))
					{
						CT_SdtRun sdt = a as CT_SdtRun;
						var list = sdt.sdtPr.Items;
						for (int k = 0; k < list.Count; k++)
						{
							var b = list[k];
							if (b.GetType() == typeof(CT_String))
							{
								var str = b as CT_String;
								if (str.val == title)
								{
									((CT_R)sdt.sdtContent.Items[0]).Items.Clear();
									((CT_R)sdt.sdtContent.Items[0]).AddNewT().Value = text;
								}
							}
						}
					}
				}
			}
			else if (item.GetType() == typeof(CT_Tbl))
			{
				CT_Tbl tbl = item as CT_Tbl;
				ArrayList arr = tbl.Items1;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j] as CT_Row;
					if (a != null)
					{
						var cells = a.Items;

						for (int k = 0; k < cells.Count; k++)
						{
							var cell = cells[k] as CT_Tc;
							if (cell != null)
							{
								var c_ps = cell.Items;
								for (int h = 0; h < c_ps.Count; h++)
								{
									var c_p = c_ps[h] as CT_P;
									if (c_p != null)
									{
										setValueToContentControl1(c_ps, title, text);
									}
								}
							}
						}
					}
				}
			}
		}
	}

	/// <summary>
	/// 给word文档的标签赋值,如果value为null,则删除标签
	/// </summary>
	/// <param name="body"></param>
	/// <param name="mark">标签名</param>
	/// <param name="value">要赋的值</param>
	/// <returns></returns>
	public static bool SetValueToBookmark(this CT_Body body, string mark, string value)
	{
		return replacebookmark1(body.Items, mark, value);
	}
	private static bool replacebookmark1(ArrayList items, string mark, string value)
	{
		string id = null;
		CT_RPr rpr = null;
		CT_P s_p = null;
		for (int i = 0; i < items.Count; i++)
		{
			var item = items[i];
			if (item.GetType() == typeof(CT_P))
			{
				var p = item as CT_P;
				var arr = p.Items;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j];
					if (a.GetType() == typeof(CT_Bookmark))
					{
						if ((a as CT_Bookmark).name == mark)
						{
							id = (a as CT_Bookmark).id;
							s_p = p;
						}
					}
					if (id != null)
					{
						if (a.GetType() == typeof(CT_R))
						{
							rpr = (a as CT_R).rPr;
						}
						if (a.GetType() == typeof(CT_Bookmark))
						{
							if ((a as CT_Bookmark).id == id)
							{
								arr.RemoveAt(j);
								j--;
							}
						}
						else if (a.GetType() != typeof(CT_MarkupRange))
						{
							arr.RemoveAt(j);
							j--;
						}
						else
						{
							if ((a as CT_MarkupRange).id == id)
							{
								if (value != null)
								{
									CT_R n_r = p.InsertNewR(j - 1);
									n_r.rPr = rpr;
									n_r.AddNewT().Value = value;
								}
								arr.RemoveAt(j);
								id = null;
								rpr = null;
								return true;

							}
						}
					}
				}
			}
			else if (item.GetType() == typeof(CT_MarkupRange))
			{
				if (id != null)
				{
					if ((item as CT_MarkupRange).id == id)
					{
						if (value != null)
						{
							CT_R n_r = s_p.AddNewR();
							n_r.rPr = rpr;
							n_r.AddNewT().Value = value;
						}
						items.RemoveAt(i);
						id = null;
						rpr = null;
						return true;
					}
				}
			}
			else if (item.GetType() == typeof(CT_Tbl))
			{
				CT_Tbl tbl = item as CT_Tbl;
				ArrayList arr = tbl.Items1;
				for (int j = 0; j < arr.Count; j++)
				{
					var a = arr[j] as CT_Row;
					if (a != null)
					{
						var cells = a.Items;

						for (int k = 0; k < cells.Count; k++)
						{
							var cell = cells[k] as CT_Tc;
							if (cell != null)
							{
								var c_ps = cell.Items;
								for (int h = 0; h < c_ps.Count; h++)
								{
									var c_p = c_ps[h] as CT_P;
									if (c_p != null)
									{
										bool temp = replacebookmark1(c_ps, mark, value);
										if (temp == true)
										{
											return true;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return false;
	}

	public class ContentControl
	{
		public string Title { set; get; }
		public string Tip { set; get; }
		public string Text { set; get; }
	}

}

标签:控件,arr,word,++,Items,npoi,var,null,CT
From: https://www.cnblogs.com/springsnow/p/18504146

相关文章

  • 解决Mysql:ERROR 1045 (28000):Access denied for user ‘root‘@‘localhost‘ (usin
    遇到 ERROR1045(28000):Accessdeniedforuser'root'@'localhost'(usingpassword:NO) 错误时,通常是因为尝试以root用户身份登录MySQL时没有提供密码或提供的密码不正确。以下是解决此问题的步骤:检查是否设置了密码:如果从未为root用户设置过密码,可以尝试在命......
  • C2W4.LAB.Word_Embedding.Part1
    理论课:C2W4.WordEmbeddingswithNeuralNetworks文章目录WordEmbeddingsFirstSteps:DataPreparationCleaningandtokenizationSlidingwindowofwordsTransformingwordsintovectorsforthetrainingsetMappingwordstoindicesandindicestowordsGett......
  • wordpress接入腾讯云COS,50G月免费流量
    对象存储COS是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持HTTP/HTTPS协议访问的分布式存储服务。腾讯云COS的存储桶空间无容量上限,无需分区管理,适用于CDN数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景,适用于网站需要实时访问、频繁访......
  • 【2024有效】WordPress忘记密码找回登录密码的最简单有效的方法
    这个找回Wordpress后台密码密的方法,前提是,可以操作数据。 最近忘记了极客侠网站登陆密码,还是按照以前的方法,进入数据库直接修改数据库,但是现在wordpress密码的加密不是简单的MD5所以不能用一个md5加密好的密码去替换数据库,这里的关键所在就是不知道现在的加密方式,于是又百......
  • 如何借助前端表格控件助力企业实现财务数字化转型
    最新技术资源(建议收藏)https://www.grapecity.com.cn/resources/前言在当今快速变化的经济环境中,记账软件对个人和企业的重要性愈发突出。对于个人而言,它可以帮助用户实时掌握财务状况,促进合理消费和有效储蓄,提升财务管理能力。对于企业,记账软件不仅提高了财务透明度和......
  • 真题练习29-Word字处理-全国计算机等级考试一级计算机基础及MS Office应用考试【汪老
    第29组请根据题目要求,完成下列操作:在考生文件夹下打开文档word.docx,按照要求完成下列操作并以该文件名(word.docx)保存文档。1.将文中所有错词“北平”替换为“北京”;设置上、下页边距各为3厘米。2.将标题段文字(“2009年北京市中考招生计划低于10万人”)设置为蓝色(标准色)、三号......
  • 题解:SP25334 NPC2015A - Eefun Guessing Words
    涉及知识点:字符串处理。解题思路记录每个字符出现的第$1$个位置和最后$1$个位置,询问时比较大小即可。代码#include<bits/stdc++.h>//#defineintlonglong#definell__int128#definedbdouble#defineldblongdouble#definevovoid#defineendl'\n'#defin......
  • .NET 开源扁平化、美观的 C/S 控件库
    前言给大家推荐一个优秀的控件集,它基于.NETFramework4.0,采用纯原生开发,不包含任何第三方插件或类库。该控件集涵盖了常用的窗体和控件,同时还包括工业工具和类Web控件。使用这套控件库我们可以快速的搭建一个漂亮的应用程序。项目介绍HZHControls包含了200多个控件、窗......
  • 实现Qtextedit控件大小改变时候希望不重新绘制
    实现Qtextedit控件大小改变时候希望不重新绘制4.备选方案5.完整示例6.总结要在QTextEdit控件大小改变时防止其重新绘制,可以通过创建一个自定义的QTextEdit子类,并重载相关事件来控制绘制行为。以下是实现这一目标的详细步骤和示例代码:创建自定义的QTextEdit......
  • 如何使用格式工厂将 PDF 转换为 Word 文档
    格式工厂是一款多功能的多媒体文件转换工具,它不仅可以转换音频和视频文件,还可以处理文档格式之间的转换。下面是一篇详细的教程,简鹿办公教你如何使用格式工厂将PDF文档转换为Word(.docx)格式。需要注意的是,如果PDF文件是由扫描件组成的图片,则可能无法直接转换为可编辑的文本......