一、 需求说明
1、 根据word文档中的层级关系设置对应的层级节点(默认最多4层);
2、 点击模块库节点,展开节点,点击右键操作选中节点所在的文件。
3、 增加模块、删除模块、修改模块、查看模块
二、功能实现
委托模板库主要包括模块库的生成、对模块库word文档的操作。
委托模板库:如下图,是模块库的生成界面。
实现逻辑:
1、 获取存放模块文件的路径,获取路径下的模块文件,根据系统文件夹下文件默认方法排序;
2、 循环遍历文件提取文件名和文件路径,遍历获取文件的段落内容,并获取段落层级编号;
3、 根据层级编号判断当前段落属于几级节点,并追加到List<KeyValuePair<string, string>>中;
4、 根据List<KeyValuePair<string, string>>中的数据,给树形添加节点。
部分代码展示:
图:List<KeyValuePair<string, string>>中的数据
/// <summary>
/// 读取树形(模块库)的层级结构
/// </summary>
public void getFileContent()
{
string path = (System.Environment.CurrentDirectory).Replace(@"\", @"/") + "../../../File/EntrustModular/EnturstPresentation"; //html 图片路径
string[] files = Directory.GetFiles(path);//获取指定路径下的文件
Array.Sort(files, new FileNameSort());// 文件名的升序
if (files.Length > 0)
{
for (int i = 0; i < files.Length; i++)
{
var SetFileName = Path.GetFileName(files[i]);//文件名
filename = SetFileName;
string path1 = System.Windows.Forms.Application.StartupPath + "../../../File/EntrustModular/EnturstPresentation/" + SetFileName;
try
{
oWord = new Word.Application();
oWord.Visible = false;
oDoc = oWord.Documents.Open(path1);
if (null == oDoc)
return;
for (int k = 1; k <= oDoc.Sections.Count; k++)
{
//---------------获取节点的名称和编号-----------
string temp = oDoc.Sections[k].Range.Text.Trim();
int index = temp.IndexOf('\r');
num = temp.Substring(0, index < 0 ? temp.Length : index);
for (int a = 0; a < num.Length; a++)
{
if ((int)num[a] > 127)//用ASCII码判断,在 ASCII码表中,英文的范围是0-127,而汉字则是大于127。
{
num1 = num.Substring(0, a);//根据这个范围可以判断。然后获取之前的字符。
break;
}
}
var str = num1.Split('.')[0];
int numlength = 0;
if (str.Length == 1)
{
numlength = num1.Length;
}
else if (str.Length == 2)
{
numlength = num1.Length - 1;
}
if (numlength == 2)
{
firstTitle = num;
m_dicFile.Add(new KeyValuePair<string, string>(firstTitle, filename));
//m_dicFile.Add(firstTitle, filename);
}
else if (numlength == 3)
{
twoTitle = num;
m_dicFile.Add(new KeyValuePair<string, string>(twoTitle, firstTitle));
//m_dicFile.Add(twoTitle, firstTitle);
}
else if (numlength == 5)
{
threeTitle = num;
m_dicFile.Add(new KeyValuePair<string, string>(threeTitle, twoTitle));
//m_dicFile.Add(threeTitle, twoTitle);
}
else if (numlength == 7)
{
fourTitle = num;
m_dicFile.Add(new KeyValuePair<string, string>(fourTitle, threeTitle));
//m_dicFile.Add(fourTitle, threeTitle);
}
}
if (null != oDoc)
{
oDoc.Close();
}
//关闭Office
oWord.Quit();
}
catch (Exception eeee)
{
MessageBox.Show(eeee.ToString());
}
}
}
}
点击模板库节点,展开节点,点击右键操作选中节点。
点击查看模块以只读的方式打开文件
选择任意节点点击右键点击添加模块,弹出一个带input的提示框,输入名称,点击确定后打开进行编辑。如果文档内容为空,给出提示框,直接点击关闭,删除当前文件。如果文件不为空,点击保存更新节点
点击修改,打开文档进行编辑,点击保存,如果模块库中存在,弹出提示框,点击确定更新节点。
点击删除,提示是否确定删除,点击确定删除指定节点对应的文件。
三、经典代码
实时更新树形关键代码
四、开发过程中遇到的问题与总结
上次提交的项目根据客户的反馈,发现项目的功能需求没有理解到位,导致后期的项目无法进行,这次完全把上次的代码推翻,但比起第一次还是相对轻松,花费的时间也相对较少,因为逻辑上已经没有太大的问题。这次完成过程中主要的问题还是代码的优化,中途更改了多次,因为以前没有做过类似的项目,对于代码的优化方面知识比较欠缺。关于代码的优化主要就是删除冗余的代码,把共同需要的代码和调用多次的代码整理、整合,提升程序的运行速度,让客户更好的体验。