所以,我将这个单词模板作为我的应用程序中的资源。 我想打开它来创建新文档,但不知道如何做到这一点。
以下代码显然不起作用,因为add方法需要一个文件路径(而不是资源byte []对象...
object tFalse = false;
object missing = System.Reflection.Missing.Value;
Word.Application app = null;
Word.Document document = null;
object template = Resources.MyTemplate;
document = app.Documents.Add(ref template, ref tFalse, ref missing, ref missing);
但是如何以正确的方式访问此资源文件?
答案 0 :(得分:0)
以下是我在大多数情况下的表现。我把工作遗漏在中间,只是打开和关闭。
private void ProcessWord()
{
object missing = System.Reflection.Missing.Value;
object readOnly = false;
object isVisible = false;
object fileName = "C:\\temp.dot";
object fileNameSaveAs = "C:\\temp.doc";
object fileFormat = WdSaveFormat.wdFormatRTF;
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Documents oDocTmp = oWord.Documents;
oWord.Visible = false;
//Open the dot file as readonly
Document oDoc = oDocTmp.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
//...do some work
//Save the doc
oDoc.SaveAs(ref fileNameSaveAs, ref fileFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// close the open document
oDoc.Close(ref saveChanges, ref missing, ref missing);
// quit word
oWord.Quit(ref saveChanges, ref missing, ref missing);
}
你还应该研究清理内存的东西,类似于:
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(oWord);
Marshal.FinalReleaseComObject(oDocTmp);
可能不是最好的做法,但它比以前更成功。
答案 1 :(得分:0)
您可以将模板另存为dot
文件,并按照以下说明直接使用模板文件路径:
object tmeplateFilePath = @"D:\YourTemplateFolder\YourTemplate.dot";
var wordApp = new Word.Application();
Word.Document doc = wordApp.Documents.Add(tmeplateFilePath);