惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
Google DeepMind News
Google DeepMind News
V
V2EX
B
Blog RSS Feed
有赞技术团队
有赞技术团队
博客园 - Franky
美团技术团队
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
云风的 BLOG
云风的 BLOG
L
LangChain Blog
GbyAI
GbyAI
The Cloudflare Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Stack Overflow Blog
Stack Overflow Blog
博客园 - 【当耐特】
The Register - Security
The Register - Security
大猫的无限游戏
大猫的无限游戏
D
Docker
Vercel News
Vercel News
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
N
Netflix TechBlog - Medium
博客园_首页
A
About on SuperTechFans
J
Java Code Geeks
量子位
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
Recent Announcements
Recent Announcements
G
Google Developers Blog
小众软件
小众软件
博客园 - 叶小钗
WordPress大学
WordPress大学
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
F
Full Disclosure
Jina AI
Jina AI
H
Help Net Security

博客园 - springsnow

Vue3中 watch、watchEffect 详解 如何使用 Vue SFC Playground toRefs学习 Vue3中如何响应式解构 props useTemplateRef使用 以后台方式启动RealVNC 在VS2022和VS2012共存的电脑上安装VS212扩展注意事项 VS中配置AnkhSVN源代码比较文件排列方式 使用VSCode撰写和发布博客园文章 DBever导入越南文Excel 复制对象中的一部分属性给另一个对象(对象部分属性解构到新对象) 使用metaWebBlog接口实现博客文章同步 .Net Core3.1上用EFCore的反向工程生成 水淼·文件批量处理器 如何高效的在博客园上编写MD格式的博客(插件pycnblog,推荐) 自动备份软件 —— Syncovery 7.98s Pro、Enterprise VMware 第三方百度网盘客户端 PanDownload、速盘、panlight 本地电脑视频播放器推荐PotPlayer、KMPlayer
npoi读取word 内容控件
springsnow · 2024-10-26 · via 博客园 - springsnow
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; }
	}

}