如何使用c#中的图像在Excel工作表中设置单元格?

时间:2016-03-24 04:15:34

标签: c# excel

我正在尝试使用Bytescout库将图像插入到Excel工作表中。但它没有发生。

我的要求是创建新的Excel文件,然后插入包含图片的数据。我只想要任何一种方法,比如任何图书馆,不仅仅是Bytescout。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码将图像和图表添加到使用ByteScout Spreadsheet SDK生成的XLX / XLSX电子表格中:

Visual Basic .NET中的

Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.IO
Imports System.Text
Imports Bytescout.Spreadsheet

Class Program
    Friend Shared Sub Main(args As String())
        ' Create spreadsheet
        Dim doc As New Spreadsheet()
        ' Add worksheet
        Dim worksheet As Worksheet = doc.Worksheets.Add()

        ' Put an image on the worksheet with 10 pixel margin from the top-left corner of the worksheet
        worksheet.Pictures.Add("image1.jpg", 10, 10)
        ' Put second image to 200 pixel offset and resize it to 250x200 px
        worksheet.Pictures.Add("image2.jpg", 200, 200, 250, 200)

        ' Save document
        doc.SaveAs("output.xls")

        ' Close spreadsheet
        doc.Close()

        ' Open generated XLS document in default application
        Process.Start("output.xls")

        doc.Dispose()
    End Sub
End Class

在C#中:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Bytescout.Spreadsheet;
using Bytescout.Spreadsheet.MSODrawing;

namespace AddImages
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create spreadsheet
            Spreadsheet doc = new Spreadsheet();
            // Add worksheet
            Worksheet worksheet = doc.Worksheets.Add();

            // Put an image to "C3" cell
            PictureShape shape = worksheet.Pictures.Add(2, 2, "image1.jpg");

            // Make the picture "floating". It will be not moved if you move or resize the "C3" cell
            shape.PlacementType = Placement.FreeFloating;

            // Make the picture brighter
            shape.Brightness = 0.8f;

            // Put second image to "K11" cell
            shape = worksheet.Pictures.Add(10, 10, "image2.jpg");

            // Make the picture bound to the cell. It will be moved along with the "K11" cell
            shape.PlacementType = Placement.Move;

            // Crop 10% from left and right side of the image
            shape.CropFromLeft = 0.1f;
            shape.CropFromRight = 0.1f;

            // Save document
            doc.SaveAs("output.xls");

            // Close spreadsheet
            doc.Close();

            // Open generated XLS document in default application
            Process.Start("output.xls");

            doc.Dispose();
        }
    }
}

有关更多代码示例,请浏览Spreadsheet SDK online documentation - *高级示例.. *部分,了解更多源代码示例,其中包括向新旧电子表格添加图片,添加图表等功能。