我正在使用 openXml SDK 创建一个简单的 word 文档。 到目前为止它正在工作。 现在我如何从我的文件系统添加一个图像到这个文档?我不在乎它在文档中的位置,它就在那里。 谢谢! 这是我目前所拥有的。
string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
//create the body
Body body = new Body();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();
DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
runParagraph.Append(text_paragraph);
p.Append(runParagraph);
body.Append(p);
mainPart.Document.Append(body);
mainPart.Document.Save();
}
最佳答案
这里有一个方法可以比上面发布的 msdn 页面中描述的方法更简单,此代码是在 C++/CLI 中,但当然你可以在 C# 中编写等效的代码
WordprocessingDocument^ doc = WordprocessingDocument::Open(doc_name, true);
FileStream^ img_fs = gcnew FileStream(image_path, FileMode::Open);
ImagePart^ image_part = doc->MainDocumentPart->AddImagePart(ImagePartType::Jpeg);
image_part->FeedData(img_fs);
Run^ img_run = doc->MainDocumentPart->Document->Body->AppendChild(gcnew Paragraph())->AppendChild(gcnew Run());
Vml::ImageData^ img_data = img_run->AppendChild(gcnew Picture())->AppendChild(gcnew Vml::Shape())->AppendChild(gcnew Vml::ImageData());
img_data->RelationshipId = doc->MainDocumentPart->GetIdOfPart(image_part);
doc->Close();
关于c# - DocumentFormat.OpenXml 将图像添加到 word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5995107/