c# - DocumentFormat.OpenXml 将图像添加到 word 文档

标签 c# asp.net openxml openxml-sdk

我正在使用 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/

相关文章:

c# - 我的 Pandigital To Roman Number 不工作

c# - 处理 Quartz.NET 的正确方法?

c# - Parallel.ForEach 错误行为

c# - OpenXML/EPPlus - 在 .Net 中创建 PivotCache

xml - 直接将单个 XML 文件转换为 DOCX

c# - 在 c#.net 中使用字符串

c# - 如何从 C#.net 传递包含\n 和\t 的长文本的 javascript 参数

c# - DataTable 加入所有行数据

c# - 在 OpenXML (excel) 中创建自定义列宽

c# - 为动态生成的复选框设置 css 类