Canalblog
Editer l'article Suivre ce blog Administration + Créer mon blog
Publicité
SpireXLS
14 juin 2011

Insert Image in Excel and Read Image with C#

Actually, people would like to read some articles or documents which include several images because the images make the article or document to be more beautiful. Also, images play a very important role in an instruction because it can show how to use the tool more clearly. Therefore, it is common to insert image to documents.

As the most frequently used tool, Microsoft Office provides us with the function to insert images in Office document. Now, take Excel as example. Let's learn something about Excel image.

It is easy to insert image in Excel.

Firstly, open an Excel file or create a new one. Then, click image on Insert menu. There are several choices for you, clip arts, from files or decorative. Generally speaking, people would like to choose from files. Select an image which you want to insert from your computer. After that, the image is inserted and you can move it or change its size. Also, right click the image. The toolbar appears. You can use the tools to edit the image.

After learning how to insert image in Excel by using Microsoft, I want to show another method to insert image programmatically.

The following code shows how to insert Excel image with C# via using a component, Spire.XLS.

private void btnRun_Click(object sender, System.EventArgs e)

{

    Workbook workbook = new Workbook();

    Worksheet sheet = workbook.Worksheets[0];

    sheet.Pictures.Add(1,1,@"..\..\..\..\..\..\Data\day.jpg");

    workbook.SaveToFile("sample.xlsx");

    ExcelDocViewer(workbook.FileName);

}

private void ExcelDocViewer( string fileName )

{

    try

    {

        System.Diagnostics.Process.Start(fileName);

    }

    catch{}

}

After inserting image with C#, then we need to read the image. Then, the following code shows how to read image.

private void btnRun_Click(object sender, System.EventArgs e)

{

    Workbook workbook = new Workbook();

    workbook.LoadFromFile(@"..\..\..\..\..\..\Data\ImageSample.xls");

    Worksheet sheet = workbook.Worksheets[0];

    ExcelPicture pic = sheet.Pictures[0];

    using( Form frm1 = new Form())

    {

        PictureBox pic1 = new PictureBox();

        pic1.Image = pic.Picture;

        frm1.Width = pic.Picture.Width;

        frm1.Height = pic.Picture.Height;

        frm1.StartPosition = FormStartPosition.CenterParent;

        pic1.Dock = DockStyle.Fill;

        frm1.Controls.Add(pic1);

        frm1.ShowDialog();

    }

}

private void ExcelDocViewer( string fileName )

{

    try

    {

        System.Diagnostics.Process.Start(fileName);

    }

    catch{}

}

Publicité
Publicité
Commentaires
SpireXLS
Publicité
Publicité