如何写从字节[]使用C#Windows应用程序图像插入MS WORD [英] How to write an image from byte[] into MS WORD using C# Windows application

查看:173
本文介绍了如何写从字节[]使用C#Windows应用程序图像插入MS WORD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从的FileStream 的StreamWriter 数据写入到一个Word文件。

这是当数据是文本格式工作正常(使用的StreamWriter )。但是,当我试图同的BinaryWriter (写入图像Word文档),它错误地写入到Word文档。

在低于code lstOrderedSpares [指数] .SparePicture 是包含图像数据的字节数组。

我需要在不OPENXML一个解决方案。

这是我试过到目前为止:

下面是我的按钮,单击我的初始化数据类和列表

 私人无效btnCreateQuotation_Click(对象发件人,EventArgs的)
    {
        尝试
        {
            报价aQuotation =新报价();
            aQuotation.QuotationId = quotationId;
            aQuotation.QuotationDate = lblQuotationDateValue.Text;

        //读取从DataGridView,并增加了名单,其中,备件和GT;

            名单<备件和GT; lstOrderedSpares =新的名单,其中,备件和GT;();
            如果(dataGridView1.Rows.Count大于0)
            {
                的foreach(在dataGridView1.Rows的DataGridViewRow博士)
                {
                    饶aSpare =新的备用();
                    aSpare.Sa preSerialNumber = dr.Cells [SlNo] Value.ToString()。
                    aSpare.SparePartId = dr.Cells [SparePartID] Value.ToString()。
                    aSpare.SparePicture =(字节[])dr.Cells [SparePicture]值。
                    aSpare.SpareDescription = dr.Cells [SpareDescription] Value.ToString()。
                    aSpare.EURPrice = Convert.ToDouble(dr.Cells [EURPrice] Value.ToString());
                    aSpare.Quantity = Convert.ToDouble(dr.Cells [数量] Value.ToString());
                    aSpare.TotalPrice = Convert.ToDouble(dr.Cells [TotalPrice] Value.ToString());
                    aSpare.DeliveryCharge = Convert.ToDouble(txtDeliveryCharge.Text.Trim());
                    aSpare.Vat = txtVAT.Text.Trim();
                    aSpare.INRPrice = Convert.ToDouble(dr.Cells [INRPrice] Value.ToString());
                    lstOrderedSpares.Add(aSpare);
                }
            }

            联系aContact =新联系();
            aContact.CompanyName = txtCustomerName.Text.Trim();
            aContact.ContactName = cmbContactPersonName.Text;
            aContact.ContactId = Convert.ToInt32(lblContactPeronIdValue.Text);
            aContact.CompanyId = Convert.ToInt32(lblCustomerIDValue.Text);

            字符串文件名=SparePart_+ aQuotation.QuotationId +_;
            字符串fileNameWithPath =C:\\ \\语录\\ SpareQuotations+文件名;
            如果(isaddedtodb)
            {
                CreateDocument(aQuotation,aContact,lstOrderedSpares,fileNameWithPath);

                fileNameWithPath = fileNameWithPath + aContact.CompanyName.Trim()+的.doc;
                btnCreateQuotation.Visible = FALSE;
                this.Hide();
                //启动MS Word中打开该文档
                System.Diagnostics.Process.Start(fileNameWithPath);
            }
        }
        赶上(例外objEx)
        {

        }
    }
 

和这里是 CreateDocument 方法,将数据写入到Word文档。

 私人无效CreateDocument(报价aQuotation,联系aContact,
                                名单<备件和GT; lstOrderedSpares,串fileNameWithPath)
    {
        尝试
        {
            _Application oWord =新Microsoft.Office.Interop.Word.Application();
            _document ODOC = oWord.Documents.Add();
            oWord.Visible = TRUE;


            //修改secondparameter中包括文件​​名客户名称
            fileNameWithPath = fileNameWithPath + aContact.CompanyName.Trim()+的.doc;

            //插入文本
            范围RNG = oDoc.Range();
            rng.Text =TSV /+ aQuotation.EnquiredBy.ToString()+/ JS /+ aQuotation.QuotationId
                    +/备件+\ t+\ t+\ t+\ t+\ t+ aQuotation.QuotationDate;
            //oWord.Selection.EndKey();
            //oWord.Selection.TypeParagraph();
            rng.InsertBreak();
            rng.Text =到;
            rng.InsertBreak();
            rng.Text =米/秒。+ aContact.CompanyName +,;
            rng.InsertBreak();
            rng.Text = aContact.AddressLine1 +,;
            rng.InsertBreak();
            rng.Text = aContact.AddressLine2 +,;
            rng.InsertBreak();
            rng.Text = aContact.City +,+ aContact.State +,;
            rng.InsertBreak();
            rng.Text = aContact.Country + - + aContact.PinNo;
            rng.InsertBreak();
            rng.Text =电话:+ aContact.PhoneNo;
            rng.InsertBreak();
            rng.Text =手机号码:+ aContact.MobileNo;
            rng.InsertBreak();
            rng.InsertBreak();

            //称呼和主题

            rng.Text =\ t+\ t+亲切关怀+ aContact.ContactName;
            rng.InsertBreak();
            rng.Text =尊敬的先生,;
            rng.InsertBreak();
            rng.Text =子:+ aQuotation.Subject;
            rng.InsertBreak();
            rng.Text =参考:您的电子邮件询问DT:+ aQuotation.EmailEnquiredDate;
            rng.InsertBreak();
            rng.Text =感谢您的宝贵电子邮件询问DT。+ aQuotation.EmailEnquiredDate
                             +供应备件为你.........能力,
                             +FABRIK号Sl的编号:..................;
            rng.InsertBreak();
            rng.InsertBreak();
            INT europeancount = 0;
            对于(INT指数= 0;指数< lstOrderedSpares.Count;指数++)
            {
                如果(lstOrderedSpares [指数] .INRPrice == 0.00)
                {
                    europeancount ++;
                }
            }

            rng.Text =a)我们想通知你,下面的+ europeancount +
                             备件可以直接在欧元提供。
            rng.InsertBreak();
            rng.InsertBreak();

            INT tempslno1 = 0;
            对于(INT指数= 0;指数< lstOrderedSpares.Count;指数++)
            {
                如果(lstOrderedSpares [指数] .INRPrice == 0.00)
                {
                    tempslno1 ++;
                    rng.Text = tempslno1 +。 + lstOrderedSpares [指数] .SpareDescription.ToUpper()+
                                 :产品编号:+ lstOrderedSpares [指数] .SparePartId +\ t+
                                 Math.Round(lstOrderedSpares [指数] .EURPrice)+ lblEuroSymbol.Text +(+
                    新NumberToEnglish()changeCurrencyToWords(Math.Round(lstOrderedSpares [指数] .EURPrice))+);

                    //从一个字节数组中插入的图片,你需要使用剪贴板粘贴
                    对象endOfContent = oDoc.Content.End  -  1;
                    范围rngPic = oDoc.Range(endOfContent);
                    //这是使用方法来转换的ByteArray成图像,并粘贴到文档中
                    图片sparePicture = ByteArrayToImage(lstOrderedSpares [指数] .SparePicture);
                    Clipboard.SetDataObject(sparePicture);
                    rngPic.Paste();
                    rng.InsertBreak();
                }
            }
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =所报价格出厂价。
            rng.InsertBreak();
            rng.Text =货运/快递,保险,关税,任何和额外的所有其他费用+
                             客户帐户。;
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =HOW TO ORDER: - 请赞成注册您的订单......;
            rng.InsertBreak();
            rng.Text =付款方式: - 全部预付款免受....形式发票+通过他们的银行家......;
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =交付/调度:在收到付款之日起2个星期。
            rng.InsertBreak();
            rng.Text =万一要是你有...帐户,然后亲切地提帐号,+
                             因为这将是经济的,如果通过送......;
            rng.Text =请提供你的'IEC code号'。
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =b)我们想通知你,以下备件可以从前股票提供+在INR我们的办公室;
            rng.InsertBreak();
            INT tempslno2 = 0;
            对于(INT指数= 0;指数< lstOrderedSpares.Count;指数++)
            {

                如果(lstOrderedSpares [指数] .INRPrice!= 0.00)
                {
                    tempslno2 ++;
                    rng.Text = tempslno2 +。 + lstOrderedSpares [指数] .SpareDescription.ToUpper()+
                                 :产品编号:+ lstOrderedSpares [指数] .SparePartId +\ t+
                                 Math.Round(lstOrderedSpares [指数] .INRPrice)++ lblINRSymbol.Text +(+
                    新NumberToEnglish()changeNumericToWords(Math.Round(lstOrderedSpares [指数] .INRPrice))+);

                    //从一个字节数组中插入的图片,你需要使用剪贴板粘贴
                    对象endOfContent = oDoc.Content.End  -  1;
                    范围rngPic = oDoc.Range(endOfContent);
                    //这是使用方法来转换的ByteArray成图像,并粘贴到文档中
                    图片sparePicture = ByteArrayToImage(lstOrderedSpares [指数] .SparePicture);
                    Clipboard.SetDataObject(sparePicture);
                    rngPic.Paste();
                    rng.InsertBreak();
                }
            }

            rng.Text =价格报价前我们的办公室;
            rng.InsertBreak();
            rng.Text =税:增值税TNGST @+ lstOrderedSpares [0] .Vat +%的额外;
            rng.InsertBreak();
            rng.Text =交货/发货:收到订单与支付;
            rng.Text =送货/快递费用 - 额外的+ lstOrderedSpares [0] .DeliveryCharge.ToString()+
                            /  - ;
            rng.InsertBreak();
            rng.Text =命令和放大器;付款可能,请释放有利于...;
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =付款方式:全部预付款由电子转账按以下详细信息的方式:;
            rng.InsertBreak();
            rng.Text =当前账号:......;
            rng.InsertBreak();
            rng.Text =IFSC code:..........;
            rng.InsertBreak();
            rng.Text =账户持有人名称:.........
            rng.InsertBreak();

            rng.Text =\ t+\ t+\ t+或;
            rng.InsertBreak();
            rng.Text =通过汇票的方式;
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =要约有效期提前30天;
            rng.InsertBreak();
            rng.Text =感谢你,等待你宝贵的指导,以满足您的需求以及时间。
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text =此致;
            rng.InsertBreak();

            oWord.Selection.EndKey();
            oWord.Selection.TypeParagraph();

            oDoc.SaveAs(fileNameWithPath); //如果你要创建一个文档
            oDoc.Close();
            oWord.Quit();
        }
        赶上(例外objEx)
        {

        }
    }

    公众形象ByteArrayToImage(byte []的byteArrayIn)
    {
        MemoryStream的毫秒=新的MemoryStream(byteArrayIn);
        图像returnImage = Image.FromStream(毫秒);
        returnImage = ResizeImage(returnImage,新的大小(30,30));
        返回returnImage;
    }

    公共静态图像ResizeImage(图片imgToResize,尺寸大小)
    {
        回报(图)(新位图(imgToResize,大小));
    }
 

解决方案
  

当你创建一个文件,例如:C:\ TEMP \ MyWordDoc.doc和写入数据到它   使用FileStream和StreamWriter,你实际编写   信息到文本文件

     

的DOC或DOCX文件扩展名会导致Microsoft Word中打开该文件,   但它不是在Word格式,它只是纯文本。

您需要使用MS Word对象模型将图片添加到Word文档。:要做到这一点参考的Microsoft.Office.Interop.Word NET的DLL在您的项目,并尝试这个code:

 使用的Microsoft.Office.Interop.Word;
使用System.IO;

私人无效btnCreateQuotation_Click(对象发件人,EventArgs的)
{
    VAR spareList =新的名单,其中,备件和GT;();
    spareList.Add(新备用{SparePicture = ImageToByteArray(Image.FromFile(@C:\ TEMP \ 11.png))});
    spareList.Add(新备用{SparePicture = ImageToByteArray(Image.FromFile(@C:\ TEMP \ 1.png))});
    CreateDocument(@C:\ TEMP \ MyWordDoc.docx,spareList);
}

公共无效CreateDocument(字符串docFilePath,名单,其中,备件和GT; lstOrderedSpares)
{
    Microsoft.Office.Interop.Word._Application oWord =新Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word._Document ODOC = oWord.Documents.Add(); //如果你要创建一个文档
    //Microsoft.Office.Interop.Word._Document ODOC = oWord.Documents.Open(docFilePath,只读:假的,可见的:真正的); //如果你打开​​一个文档

    //要了解怎么回事,而填充Word文档设置可见=真
    oWord.Visible = TRUE;

    //插入文本
    对象oMissing = System.Reflection.Missing.Value;
    VAR oPara1 = oDoc.Content.Paragraphs.Add(REF oMissing);
    oPara1.Range.Text =一个文本;
    oPara1.Range.InsertParagraphAfter();

    //这是使用方法插入来自字节数组到MS Word,你需要的图片
    //转换的ByteArray成图像,并使用剪贴板粘贴到文档中
    图像sparePicture = ByteArrayToImage(lstOrderedSpares [0] .SparePicture);
    Clipboard.SetDataObject(sparePicture);
    VAR oPara2 = oDoc.Content.Paragraphs.Add(REF oMissing);
    oPara2.Range.Paste();
    oPara2.Range.InsertParagraphAfter();

    //插入一些文字
    VAR oPara3 = oDoc.Content.Paragraphs.Add(REF oMissing);
    oPara3.Range.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); //如果你要创建一个文档
    //oDoc.Save(); //如果你打开​​一个文档
    oDoc.Close();
    oWord.Quit();
}

公众形象ByteArrayToImage(byte []的byteArrayIn)
{
    MemoryStream的毫秒=新的MemoryStream(byteArrayIn);
    图像returnImage = Image.FromStream(毫秒);
    返回returnImage;
}

//方法我用它来测试加载图像从磁盘转换为字节[]的和将它们插入到Word
公共字节[] ImageToByteArray(System.Drawing.Image对象imageIn)
{
    byte []的结果= NULL;
    使用(MemoryStream的毫秒=新的MemoryStream())
    {
        imageIn.Save(MS,System.Drawing.Imaging.ImageFormat.Png);
        结果= ms.ToArray();
    }
    返回结果;
}
 

这是结果:

I have tried to write data from FileStream, StreamWriter to a word file.

It's working fine when the data is text format(using StreamWriter). But when I tried the same with Binarywriter (for writing image to word doc) it's writing incorrectly to the word document.

In below code lstOrderedSpares[index].SparePicture is the byte array containing the image data.

I need a solution without OPENXML.

This is what I have tried so far :

Here is my button click where i am initializing the data to classes and List

 private void btnCreateQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            Quotation aQuotation = new Quotation();
            aQuotation.QuotationId = quotationId;
            aQuotation.QuotationDate = lblQuotationDateValue.Text;

        //Reading from Datagridview and adding to List<Spare>

            List<Spare> lstOrderedSpares = new List<Spare>();
            if (dataGridView1.Rows.Count > 0)
            {
                foreach (DataGridViewRow dr in dataGridView1.Rows)
                {
                    Spare aSpare = new Spare();
                    aSpare.SapreSerialNumber = dr.Cells["SlNo"].Value.ToString();
                    aSpare.SparePartId = dr.Cells["SparePartID"].Value.ToString();
                    aSpare.SparePicture = (byte[])dr.Cells["SparePicture"].Value;
                    aSpare.SpareDescription = dr.Cells["SpareDescription"].Value.ToString();
                    aSpare.EURPrice = Convert.ToDouble(dr.Cells["EURPrice"].Value.ToString());
                    aSpare.Quantity = Convert.ToDouble(dr.Cells["Quantity"].Value.ToString());
                    aSpare.TotalPrice = Convert.ToDouble(dr.Cells["TotalPrice"].Value.ToString());
                    aSpare.DeliveryCharge = Convert.ToDouble(txtDeliveryCharge.Text.Trim());
                    aSpare.Vat = txtVAT.Text.Trim();
                    aSpare.INRPrice = Convert.ToDouble(dr.Cells["INRPrice"].Value.ToString());
                    lstOrderedSpares.Add(aSpare);
                }
            }

            Contact aContact = new Contact();
            aContact.CompanyName = txtCustomerName.Text.Trim();
            aContact.ContactName = cmbContactPersonName.Text;
            aContact.ContactId = Convert.ToInt32(lblContactPeronIdValue.Text);
            aContact.CompanyId = Convert.ToInt32(lblCustomerIDValue.Text);

            string fileName = "SparePart_" + aQuotation.QuotationId + "_";
            string fileNameWithPath = "C:\\Quotations\\SpareQuotations\\" + fileName;
            if (isaddedtodb)
            {
                CreateDocument(aQuotation, aContact, lstOrderedSpares, fileNameWithPath);

                fileNameWithPath = fileNameWithPath + aContact.CompanyName.Trim() + ".doc";
                btnCreateQuotation.Visible = false;
                this.Hide();
                //start ms word to open the document 
                System.Diagnostics.Process.Start(fileNameWithPath);
            }
        }
        catch (Exception objEx)
        {

        }
    }

and here is the CreateDocument Method which writes data to the word document.

 private void CreateDocument(Quotation aQuotation, Contact aContact,
                                List<Spare> lstOrderedSpares, string fileNameWithPath)
    {
        try
        {
            _Application oWord = new Microsoft.Office.Interop.Word.Application();
            _Document oDoc = oWord.Documents.Add();
            oWord.Visible = true;


            //modify secondparameter to include customer name in file name 
            fileNameWithPath = fileNameWithPath + aContact.CompanyName.Trim() + ".doc";

            //Insert text
            Range rng = oDoc.Range();
            rng.Text = "TSV/" + aQuotation.EnquiredBy.ToString() + "/JS/" + aQuotation.QuotationId
                    + "/SPARES" + "\t" + "\t" + "\t" + "\t" + "\t" + aQuotation.QuotationDate;
            //oWord.Selection.EndKey();
            //oWord.Selection.TypeParagraph();
            rng.InsertBreak();
            rng.Text = "To ,";
            rng.InsertBreak();
            rng.Text = "M/s. " + aContact.CompanyName + ",";
            rng.InsertBreak();
            rng.Text = aContact.AddressLine1 + ",";
            rng.InsertBreak();
            rng.Text = aContact.AddressLine2 + ",";
            rng.InsertBreak();
            rng.Text = aContact.City + "," + aContact.State + ",";
            rng.InsertBreak();
            rng.Text = aContact.Country + "-" + aContact.PinNo;
            rng.InsertBreak();
            rng.Text = "Phone : " + aContact.PhoneNo;
            rng.InsertBreak();
            rng.Text = "Mobile No : " + aContact.MobileNo;
            rng.InsertBreak();
            rng.InsertBreak();

            //Salutation and subject

            rng.Text = "\t" + "\t" + "Kind Attention : " + aContact.ContactName;
            rng.InsertBreak();
            rng.Text = "Dear Sir,";
            rng.InsertBreak();
            rng.Text = "Sub: " + aQuotation.Subject;
            rng.InsertBreak();
            rng.Text = "Ref: your email enquiry dt: " + aQuotation.EmailEnquiredDate;
            rng.InsertBreak();
            rng.Text = "We thank you for your valuable email enquiry dt. " + aQuotation.EmailEnquiredDate
                             + " for supply of spares for your .........Capacity,"
                             + " fabrik nos Sl. No :..................";
            rng.InsertBreak();
            rng.InsertBreak();
            int europeancount = 0;
            for (int index = 0; index < lstOrderedSpares.Count; index++)
            {
                if (lstOrderedSpares[index].INRPrice == 0.00)
                {
                    europeancount++;
                }
            }

            rng.Text = "A) We wish to inform you that the following " + europeancount +
                             " spares can be supplied directly by in Euros.";
            rng.InsertBreak();
            rng.InsertBreak();

            int tempslno1 = 0;
            for (int index = 0; index < lstOrderedSpares.Count; index++)
            {
                if (lstOrderedSpares[index].INRPrice == 0.00)
                {
                    tempslno1++;
                    rng.Text = tempslno1 + "." + lstOrderedSpares[index].SpareDescription.ToUpper() +
                                 " : ARTICLE NO: " + lstOrderedSpares[index].SparePartId + "\t" +
                                 Math.Round(lstOrderedSpares[index].EURPrice) + lblEuroSymbol.Text + "(" +
                    new NumberToEnglish().changeCurrencyToWords(Math.Round(lstOrderedSpares[index].EURPrice)) + ")";

                    //To insert a picture from a byte array you need to use the Clipboard to paste it in
                    object endOfContent = oDoc.Content.End - 1;
                    Range rngPic = oDoc.Range(endOfContent);
                    //Here is the trick to convert the ByteArray into an image and paste it in the document
                    Image sparePicture = ByteArrayToImage(lstOrderedSpares[index].SparePicture);
                    Clipboard.SetDataObject(sparePicture);
                    rngPic.Paste();
                    rng.InsertBreak();
                }
            }
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "Price Quoted Ex-works .";
            rng.InsertBreak();
            rng.Text = "Freight/Courier,Insurance,duties,any and all other expenses extra to " +
                             "customers account.";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "HOW TO ORDER :- Please register your order in favour of ....";
            rng.InsertBreak();
            rng.Text = "PAYMENT :- Full payment in advance against proforma invoice from ...." + " through their bankers ..... ";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "Delivery / Dispatch: 2 Weeks from the date of receipt of payment.";
            rng.InsertBreak();
            rng.Text = "In case if you have account with ...then kindly mention the account number, " +
                             "since it will be economical if send via ....";
            rng.Text = "Please provide your 'IEC Code number'.";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "B) We wish to inform you that the following spare can be supplied from ex-stock " + "our Office in INR";
            rng.InsertBreak();
            int tempslno2 = 0;
            for (int index = 0; index < lstOrderedSpares.Count; index++)
            {

                if (lstOrderedSpares[index].INRPrice != 0.00)
                {
                    tempslno2++;
                    rng.Text = tempslno2 + "." + lstOrderedSpares[index].SpareDescription.ToUpper() +
                                 " : ARTICLE NO: " + lstOrderedSpares[index].SparePartId + "\t" +
                                 Math.Round(lstOrderedSpares[index].INRPrice) + " " + lblINRSymbol.Text + "(" +
                    new NumberToEnglish().changeNumericToWords(Math.Round(lstOrderedSpares[index].INRPrice)) + ")";

                    //To insert a picture from a byte array you need to use the Clipboard to paste it in
                    object endOfContent = oDoc.Content.End - 1;
                    Range rngPic = oDoc.Range(endOfContent);
                    //Here is the trick to convert the ByteArray into an image and paste it in the document
                    Image sparePicture = ByteArrayToImage(lstOrderedSpares[index].SparePicture);
                    Clipboard.SetDataObject(sparePicture);
                    rngPic.Paste();
                    rng.InsertBreak();
                }
            }

            rng.Text = "Price quoted ex-our office";
            rng.InsertBreak();
            rng.Text = "Taxes: VAT TNGST @ " + lstOrderedSpares[0].Vat + "% extra";
            rng.InsertBreak();
            rng.Text = "Delivery/Despatch: on receipt of order along with payment";
            rng.Text = "Delivery/Courier Charges - extra " + lstOrderedSpares[0].DeliveryCharge.ToString() +
                            "/-";                
            rng.InsertBreak();
            rng.Text = "The order & payment may please be released in favour of...";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "Payment: Full payment in advance by way of Electronic Transfer as per following details :";
            rng.InsertBreak();
            rng.Text = "Current Account Number: ......";
            rng.InsertBreak();
            rng.Text = "IFSC Code: ..........";
            rng.InsertBreak();
            rng.Text = "Name of the account holder: .........";
            rng.InsertBreak();

            rng.Text = "\t" + "\t" + "\t" + "OR";
            rng.InsertBreak();
            rng.Text = "By way of Demand Draft";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "Offer validity 30 days";
            rng.InsertBreak();
            rng.Text = "Thanking you and awaiting your valuable instructions to fulfill your needs well in time.";
            rng.InsertBreak();
            rng.InsertBreak();
            rng.Text = "Yours sincerely";
            rng.InsertBreak();

            oWord.Selection.EndKey();
            oWord.Selection.TypeParagraph();

            oDoc.SaveAs(fileNameWithPath);  //If you're creating a document
            oDoc.Close();
            oWord.Quit();
        }
        catch (Exception objEx)
        {

        }
    }

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

    public static Image ResizeImage(Image imgToResize, Size size)
    {
        return (Image)(new Bitmap(imgToResize, size));
    }

解决方案

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

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

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:\temp\11.png"))});
    spareList.Add(new Spare { SparePicture = ImageToByteArray(Image.FromFile(@"C:\temp\1.png")) });
    CreateDocument(@"C:\Temp\MyWordDoc.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)
{
    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;
}

This is the result:

这篇关于如何写从字节[]使用C#Windows应用程序图像插入MS WORD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆