我目前想以正确的顺序遍历word文档。为此,我尝试了如果&切换声明。它仍然只是通过word文档中的顺序对其进行分类。这只是一个例子。在我的情况下输出变成“blabla1”,“blabla2”,“blabla3”等。相反,我希望它是“blabla2”,“blabla1”,“blabla3”任何建议?
namespace KontraktTilTekst {
public partial class Form1: Form {
public Url url = new Url();
public bool[] success = new bool[2];
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
url.FileExist = File.Exists(url.WordPath) ? true : false; //Tjekker om urlen er der
if (url.FileExist) {
if (!String.IsNullOrEmpty(url.TxtFileName)) //Tjekker om feltet til notepadfilen ikke er tomt
{
StreamWriter NotepadFile = new StreamWriter(url.TxtPath);
Microsoft.Office.Interop.Word.Application word = new ApplicationClass();
object miss = System.Reflection.Missing.Value;
object path = url.WordPath; // <-------- Path where document is
object readOnly = false;
Document document = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss);
word.Documents.Open(url.WordPath);
foreach(ContentControl ff in document.ContentControls) {
if (ff.Title == "something2") {
NotepadFile.Write("blabla2");
} else if (ff.Title == "something1") {
NotepadFile.Write("blabla1");
} else if (ff.Title == "something3") {
NotepadFile.Write("blabla3");
}
}
NotepadFile.Close();
document.Close(ref miss, ref miss, ref miss);
word.Quit();
} else {
MessageBox.Show("Husk at give txt filen et navn");
}
} else {
//MessageBox.Show(url.FileExist.ToString());
MessageBox.Show("Prøv med en anden sti");
}
}
}
}
答案 0 :(得分:0)
有一个单独的函数来查找文档中具有指定标题的ContentControl。然后按照要查看的标题的顺序调用此函数。
private void button1_Click(object sender, EventArgs e)
{
Document wordDocument = ....;/// Your code to open document
if(HasContentControlWithTitle(wordDocument, "something2"))
{
NotepadFile.Write("blabla2");
}
if(HasContentControlWithTitle(wordDocument, "something1"))
{
NotepadFile.Write("blabla1");
}
if(HasContentControlWithTitle(wordDocument, "something3"))
{
NotepadFile.Write("blabla3");
}
}
bool HasContentControlWithTitle(Document wordDocument, string title)
{
ContentControl result = GetContentControlByTitle(wordDocument, title);
return result != null;
}
ContentControl GetContentControlByTitle(Document wordDocument, string title)
{
ContentControl result = null;
foreach(ContentControl ff in wordDocument.ContentControls)
{
if(ff.Title == title)
{
result = ff;
break;
}
}
return result;
}