How to embed file to word docx?

谁都会走 提交于 2019-12-11 10:34:02

问题


I'm trying to insert a file programmatically (*.zip for example) into an existing docx file.

I looked at the docx open library but it doesn't have the function there.

Also tried using Microsoft.Office.Interop.Word. I created a word document with a table, and I'm trying to insert a file into a cell inside the table.

Word.Application wordApp = new Word.Application();
wordApp.Visible = false;

Word.Document doc = new Word.Document();
doc = wordApp.Documents.Open(Environment.CurrentDirectory + "\\test.docx");
doc.Tables[1].Rows[2].Cells[1].Range.InsertFile((Environment.CurrentDirectory + "\\tttt.zip"));

but it caused an error:

"The file appears to be corrupted"

Can anyone have experience and help with this?


回答1:


After a lot of trial and error... The function "Range.InsertFile" doesn't actually inserts a file, it reads and appends the text into the Range.

The solution was simple - Copy paste...

using System.Collections.Specialized;
...
...
//Copy the Filename to Clipboard (setFile function uses StringCollection)
StringCollection collection = new StringCollection();
collection.Add(Environment.CurrentDirectory + "\\MyFile.zip");
Clipboard.SetFileDropList(collection);

//Paste into the selected Range.
range.Paste();

*There is also function "PasteSpecial" which didn't work (Only specific data types are supported).



来源:https://stackoverflow.com/questions/33126412/how-to-embed-file-to-word-docx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!