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

尚丹·库玛(Chandan Kumar)

我试图从数据写FileStreamStreamWriter一个字的文件。

当数据为文本格式(使用StreamWriter时,效果很好但是,当我尝试使用相同的方法Binarywriter(用于将图像写入Word文档)时,将其错误地写入了Word文档。

下面的代码lstOrderedSpares[index].SparePicture是包含图像数据的字节数组。

我需要没有OPENXML的解决方案。

到目前为止,这是我尝试过的:

这是我要在其中将数据初始化为类的按钮单击, 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)
        {

        }
    }

这是CreateDocument将数据写入Word文档的方法。

 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));
    }
杰里米·汤普森

创建文件(例如C:\ Temp \ MyWordDoc.doc)并使用FileStream和StreamWriter向其中写入数据时,实际上是在将信息写入文本文件。

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

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

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)
{
    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;
}

结果如下:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法从iOS Word应用程序将MS Word文档复制到我的应用程序

来自分类Dev

C#Windows应用程序将文本写入文件

来自分类Dev

是否可以将Word文档嵌入#Windows应用程序中?

来自分类Dev

是否可以将Word文档嵌入#Windows应用程序中?

来自分类Dev

如何使用sed替换“ word {word”或“ word} word”

来自分类Dev

将变量存储在MS Word中,并在应用程序中将其用于超链接中的变量?

来自分类Dev

如何将MS Word 2010设置为所有docx和其他类型的默认应用程序?

来自分类Dev

MS Word是否有应用程序URL协议?

来自分类Dev

将外壳输出写入MS Word文档

来自分类Dev

如何在MS Word VBA中处理多字节符号

来自分类Dev

IF AND语句在MS WORD中

来自分类Dev

使用C#Windows应用商店应用程序将文本从RichEditBox写入文件时出现问题

来自分类Dev

使用进程句柄获取MS-Word应用程序实例

来自分类Dev

语法应用程序规则Microsoft Word

来自分类Dev

在MS Word中插入PDF图像

来自分类Dev

从图像创建MS Word模板

来自分类Dev

打开Word应用程序时“使用文档”

来自分类Dev

如何调整MS Word文档中的多个图像大小?

来自分类Dev

在Windows Phone应用中填充Word的字段(Word模板)

来自分类Dev

机器中的单独Microsoft.Office.Interop.Word实例和Word应用程序

来自分类Dev

使用从Windows窗体应用程序获取的输入来填充word文档

来自分类Dev

Jupyter Notebook:如何将粘贴图像复制到MS Word中?

来自分类Dev

如何将图像转换为pdf和ms word文档C#?

来自分类Dev

在Windows 8.1下运行时,WinForm应用程序在COM调用MS Word后更改表单外观

来自分类Dev

使用宏将所有形状转换为MS Word中的图像

来自分类Dev

如何使用VSTO从另一个.NET应用程序在Word中操作事件

来自分类Dev

在C ++应用程序中的Microsoft Word中打印特定页面范围时出错

来自分类Dev

诊断MS Word的瓶颈

来自分类Dev

Word对象中的Word VBA范围

Related 相关文章

  1. 1

    无法从iOS Word应用程序将MS Word文档复制到我的应用程序

  2. 2

    C#Windows应用程序将文本写入文件

  3. 3

    是否可以将Word文档嵌入#Windows应用程序中?

  4. 4

    是否可以将Word文档嵌入#Windows应用程序中?

  5. 5

    如何使用sed替换“ word {word”或“ word} word”

  6. 6

    将变量存储在MS Word中,并在应用程序中将其用于超链接中的变量?

  7. 7

    如何将MS Word 2010设置为所有docx和其他类型的默认应用程序?

  8. 8

    MS Word是否有应用程序URL协议?

  9. 9

    将外壳输出写入MS Word文档

  10. 10

    如何在MS Word VBA中处理多字节符号

  11. 11

    IF AND语句在MS WORD中

  12. 12

    使用C#Windows应用商店应用程序将文本从RichEditBox写入文件时出现问题

  13. 13

    使用进程句柄获取MS-Word应用程序实例

  14. 14

    语法应用程序规则Microsoft Word

  15. 15

    在MS Word中插入PDF图像

  16. 16

    从图像创建MS Word模板

  17. 17

    打开Word应用程序时“使用文档”

  18. 18

    如何调整MS Word文档中的多个图像大小?

  19. 19

    在Windows Phone应用中填充Word的字段(Word模板)

  20. 20

    机器中的单独Microsoft.Office.Interop.Word实例和Word应用程序

  21. 21

    使用从Windows窗体应用程序获取的输入来填充word文档

  22. 22

    Jupyter Notebook:如何将粘贴图像复制到MS Word中?

  23. 23

    如何将图像转换为pdf和ms word文档C#?

  24. 24

    在Windows 8.1下运行时,WinForm应用程序在COM调用MS Word后更改表单外观

  25. 25

    使用宏将所有形状转换为MS Word中的图像

  26. 26

    如何使用VSTO从另一个.NET应用程序在Word中操作事件

  27. 27

    在C ++应用程序中的Microsoft Word中打印特定页面范围时出错

  28. 28

    诊断MS Word的瓶颈

  29. 29

    Word对象中的Word VBA范围

热门标签

归档