1

i'm struggling on how i could handling converting this System.Byte[] array in my table coming from my Datagridview, see the column containing the images that only display Sytem.Byte[]

enter image description here

this is the code that im using but still it only display texts.

private void ToCsV(DataGridView DGV, string filename)
    {
        try
        {
            if (DGV.Rows.Count != 0)
            {


                int RowCount = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                    } //end row loop
                } //end column loop



                Document oDoc = new Document();
                oDoc.Application.Visible = true;



                //page orintation
                oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;


                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string oTemp = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";

                    }
                }

                //table format
                oRange.Text = oTemp;

                object Separator = WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders = true;
                object AutoFit = true;
                object AutoFitBehavior = WdAutoFitBehavior.wdAutoFitContent;

                oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                      Type.Missing, Type.Missing, ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

                oRange.Select();

                oDoc.Application.Selection.Tables[1].Select();
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.InsertRowsAbove(1);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();

                //header row style
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                //add header row manually
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                }

                //table style 
                oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //header text
                foreach (Section section in oDoc.Application.ActiveDocument.Sections)
                {
                    Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
                    headerRange.Text = "your header text";
                    headerRange.Font.Size = 16;
                    headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                }

               /* string fileName = @"C:\Users\JethroPaulo\Desktop\a314bf90a43cb49873d014b00bb3672b.jpg";  //the picture file to be inserted
                Object oMissed = oDoc.Paragraphs[2].Range; //the position you want to insert
                Object oLinkToFile = false;  //default
                Object oSaveWithDocument = true;//default
                oDoc.InlineShapes.AddPicture(fileName, ref  oLinkToFile, ref  oSaveWithDocument, ref  oMissed);

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


                Image sparePicture = fetch;
                Clipboard.SetDataObject(sparePicture);
                var oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Paste();
                oPara2.Range.InsertParagraphAfter();*/
                //save the file
                oDoc.SaveAs(filename);

                //NASSIM LOUCHANI
            }
        }
        catch (Exception ex)
        {
            DialogResult result = MessageBox.Show(ex.Message.ToString(), "Critical Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }
    }
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Pau
  • 61
  • 13

3 Answers3

1

You didn't copy my answer exactly, you're missing the ByteArrayToImage

Image sparePicture = ByteArrayToImage(fetch); //<-- This is what you're missing
Clipboard.SetDataObject(sparePicture);
var oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara2.Range.Paste();
oPara2.Range.InsertParagraphAfter();

...

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

You dont show what fetch is but I'm assuming its a byte[], so to implement this:

int r = 0;
for (int c = 0; c <= ColumnCount - 1; c++)
{
    for (r = 0; r <= RowCount - 1; r++)
    {
        if (c == 5) { //Change the constant 5 to use the Student_Image column index
           DataArray[r, c] = ByteArrayToImage(DGV.Rows[r].Cells[c].Value);
        }
        else {
           DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
        }
    }
} 
Community
  • 1
  • 1
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • the fetch is a byte[] ...actually i used it already but it only read the last image inside the datagridview ... – Pau May 23 '16 at 08:30
  • You dont actually show where you insert the Image in the table, there is only commented out code to insert an image at the end. If that code was uncommented it probably would only render out the last image of the datagridview. You need to add this code inside the for-loop where you populate rows. ps best to change the function name `ToWord` as its not CSV. – Jeremy Thompson May 23 '16 at 08:38
  • im inserting the images inside the PhpMyAdmin MySql(as Blob Images) and then retrieving those to datagridview... this si the code where i populate rows. //add rows int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop but DataArray only display the value not exactly The IMAGE that i need – Pau May 23 '16 at 08:46
  • see my edit to implement it, welcome to [so] by the way! – Jeremy Thompson May 23 '16 at 08:51
  • oh one last question, @jeremy thompson, how to get List? – Pau May 23 '16 at 08:58
  • Have a look at my other answer, in the `btnCreateQuotation_Click` event I make that List before passing it to the `CreateDocument` method – Jeremy Thompson May 23 '16 at 08:59
  • Now i get it, my problem is that i want to read and load all the images at once inside the word document. the problem is i can only load them one by one using your code mr. jeremy – Pau May 28 '16 at 06:02
  • it only returns a System.Drawing.Bitmap – Pau May 28 '16 at 06:10
  • You can't put `using` around the memory stream used to create an image. An `Image` object created from a stream [will need the stream to remain open for the entire life cycle of the image object](https://msdn.microsoft.com/en-us/library/z7ha67kw(v=vs.110).aspx#Anchor_2). – Nyerguds Dec 09 '18 at 17:44
0

Mr. Jeremy's idea is a great help. the missing piece the i found is as follows:

  1. Object Missing Value - this object refers to a table that has specified cell/s which the images will be placed into. [Document.Table[1].Cells(row, col).Range]
  2. Image sparePicture - instead of using Object[,] DataArray (see the previous code above), i used rather an Image object to store the array of images, then setting it up on the Clipboard and Pasting it.
  3. InsertParagrahAfter() - using this method, i inserted the images one by one on their designated cells just like within the dataGridview.

           for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        if (c == 5)
                        {
    
                           Object oMissing = oDoc.Tables[1].Cell(r + 2, 6).Range; //the position where you want to put the images
    
                           Image sparePicture = ByteArrayToImage((byte[])DGV.Rows[r].Cells[c].Value);
                            Clipboard.SetImage(sparePicture);
                            Word.Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
                            oPara2.Range.Paste();
                            oPara2.Range.InsertParagraphAfter();
                        }
                    }
                }
    
Pau
  • 61
  • 13
0

After many hours i create Encode and Serialize and this returns a string with the src that you apply to the img.

    string img_src = data.Rows[0].IsNull("PHOTO") ? string.Format("") : string.Format("data:image/jpeg;base64,{0}", data.Rows[0]["PHOTO"].EncodeAndSerialize().Replace("\"", ""));
----------------------------    
        public static string EncodeAndSerialize<T>(this T obj) where T : new()
                {
                    var settings = new JsonSerializerSettings
                    {
                        ContractResolver = new HtmlEncodeResolver(),
                        Formatting = Newtonsoft.Json.Formatting.None
                    };
                    return JsonConvert.SerializeObject(obj, settings);
                }
George Stavrou
  • 482
  • 5
  • 11