且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 C# Windows 应用程序将 byte[] 中的图像写入 MS WORD

更新时间:2023-02-07 22:55:45

当您创建一个文件,例如 C:TempMyWordDoc.doc 并向其中写入数据时使用 FileStream 和 StreamWriter,你实际上是在写信息到文本文件.

When you create a file, eg C:TempMyWordDoc.doc and write data to it using a FileStream and StreamWriter, you're actually writing information to a text file.

doc 或 docx 文件扩展名导致 Microsoft Word 打开文件,但它不是 Word 格式,它只是纯文本.

The doc or docx file extension causes Microsoft Word to open the file, but it is NOT in Word format, its just plain text.

您需要使用 MS Word 对象模型将图片添加到 Word 文档中. 为此,请参考您项目中的 Microsoft.Office.Interop.Word .Net DLL 并尝试以下代码:

You need to use the MS Word Object Model to add pictures into a word document. To do this reference the Microsoft.Office.Interop.Word .Net DLL in your project and try this code:

using Microsoft.Office.Interop.Word;
using System.IO;

private void btnCreateQuotation_Click(object sender, EventArgs e)
{
    var spareList = new List<Spare>();
    spareList.Add(new Spare{ SparePicture  = ImageToByteArray(Image.FromFile(@"C:	emp11.png"))});
    spareList.Add(new Spare { SparePicture = ImageToByteArray(Image.FromFile(@"C:	emp1.png")) });
    CreateDocument(@"C:TempMyWordDoc.docx", spareList);
}

public void CreateDocument(string docFilePath, List<Spare> lstOrderedSpares)
{
    Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(); //If you're creating a document
    //Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Open(docFilePath, ReadOnly: false, Visible: true); //If you're opening a document

    //To see whats going on while populating the word document set Visible = true
    oWord.Visible = true;

    //Insert text
    Object oMissing = System.Reflection.Missing.Value;
    var oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara1.Range.Text = "First Text";
    oPara1.Range.InsertParagraphAfter();

    //Here is the trick to insert a picture from a byte array into MS Word you need to 
    //convert the ByteArray into an Image and using the Clipboard paste it into the document
    Image sparePicture = ByteArrayToImage(lstOrderedSpares[0].SparePicture);
    Clipboard.SetDataObject(sparePicture);
    var oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara2.Range.Paste();
    oPara2.Range.InsertParagraphAfter();

    //Insert some more text
    var oPara3 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara3.Range.Text = "Second Text" + Environment.NewLine;
    oPara3.Range.InsertParagraphAfter();

    sparePicture = ByteArrayToImage(lstOrderedSpares[1].SparePicture);
    Clipboard.SetDataObject(sparePicture);
    var oPara4 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara4.Range.Paste();
    oPara4.Range.InsertParagraphAfter();

    oDoc.SaveAs(docFilePath); //If you're creating a document
    //oDoc.Save();  //If you're opening a document
    oDoc.Close();
    oWord.Quit();
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    {
      Image returnImage = Image.FromStream(ms);
      return returnImage;
    }
}

//Method I use to test loading images from disk into byte[]'s and inserting them into word
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    byte[] result = null;
    using (MemoryStream ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        result = ms.ToArray();
    }
    return result;
}

结果如下: