5

OpenXML を使用して、Excel スプレッドシートに画像を追加できます。ただし、プログラムの残りの部分では、ClosedXML を使用してデータを追加します。列と行のインデックスを使用して、特定のセルにデータを追加できます。画像をExcelに追加できる場合(現在、セルの上にカーソルを置いているように見える別のレイヤーです)、ClosedXMLを使用してセルに追加するにはどうすればよいですか?

    //Adds an image to the excel file
    public void AddImageToExcel(SpreadsheetDocument sd, MemoryStream imagestream)
    {
        DrawingsPart dp = sd.WorkbookPart.WorksheetParts.First().AddNewPart<DrawingsPart>();
        ImagePart imgp = dp.AddImagePart(ImagePartType.Jpeg, sd.WorkbookPart.WorksheetParts.First().GetIdOfPart(dp));

        MemoryStream bmstream = new MemoryStream(imagestream.ToArray());
        bmstream.Seek(0, SeekOrigin.Begin);

        MemoryStream fs;
        using (fs = imagestream)
        {
            fs.Position = 0;
            imgp.FeedData(fs);
        }

        DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties nvdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties();
        nvdp.Id = 1025;
        nvdp.Name = "Chart Image";
        nvdp.Description = "Image";
        DocumentFormat.OpenXml.Drawing.PictureLocks piclocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
        piclocks.NoChangeAspect = true;
        piclocks.NoChangeArrowheads = true;
        DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties nvpdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties();
        nvpdp.PictureLocks = piclocks;
        DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties nvpp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties();
        nvpp.NonVisualDrawingProperties = nvdp;
        nvpp.NonVisualPictureDrawingProperties = nvpdp;

        DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
        stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

        DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill blipfill = new DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill();
        DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
        blip.Embed = dp.GetIdOfPart(imgp);
        blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
        blipfill.Blip = blip;
        blipfill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
        blipfill.Append(stretch);

        DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
        DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
        offset.X = 0;
        offset.Y = 0;
        t2d.Offset = offset;
        Bitmap bm = new Bitmap(bmstream);

        DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
        extents.Cx = ((long)bm.Width * (long)((float)914400 / bm.HorizontalResolution));
        extents.Cy = ((long)bm.Height * (long)((float)914400 / bm.VerticalResolution));
        bm.Dispose();
        t2d.Extents = extents;
        DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties sp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties();
        sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
        sp.Transform2D = t2d;
        DocumentFormat.OpenXml.Drawing.PresetGeometry prstgeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
        prstgeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
        prstgeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
        sp.Append(prstgeom);
        sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

        DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
        picture.NonVisualPictureProperties = nvpp;
        picture.BlipFill = blipfill;
        picture.ShapeProperties = sp;

        DocumentFormat.OpenXml.Drawing.Spreadsheet.Position pos = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Position();

        //The position corrosponds these numbers. X= 600000 & y = 200000 adds up to 1 cell
        pos.X = 600000;
        pos.Y = 200000;

        Extent ext = new Extent();
        ext.Cx = extents.Cx;
        ext.Cy = extents.Cy;
        AbsoluteAnchor anchor = new AbsoluteAnchor();

        Xdr.Position pp = new Xdr.Position();
        pp.X = 0;
        pp.Y = 0;


        anchor.Position = pp;
        anchor.Position = pos;
        anchor.Extent = ext;
        anchor.Append(picture);
        anchor.Append(new ClientData());
        WorksheetDrawing wsd = new WorksheetDrawing();
        wsd.Append(anchor);
        Drawing drawing = new Drawing();
        drawing.Id = dp.GetIdOfPart(imgp);
        wsd.Save(dp);
        sd.WorkbookPart.WorksheetParts.First().Worksheet.Append(drawing);
        MessageBox.Show("Excel File created");
    }

これは私が使用したコードで、どこかのスタック オーバーフローで見つけました。画像に MemoryStream を使用するように変更しました。最初に私が抱えている問題の 1 つは、メソッドにスプレッドシート ドキュメントを渡すことですが、これを修正するために ClosedXML で何ができるかわかりません。理想的には、私は簡単に言いたいです

ws.Cell(colnum, rownum).Value = AddImageToExcel(wb, ImageToMemoryStream(imagelocation));

助けてくれてありがとう!

4

3 に答える 3

5

ここで少し遅れましたが、他の誰かが見に来た場合に備えて、ClosedXML に (限定的な) 画像サポートを追加しました。

フォークは https://closedxml.codeplex.com/SourceControl/network/forks/ajwhiteway/ClosedXMLImageSupportにあります。

編集:それがどのように機能するかについていくつかの詳細を追加します。

新しいクラス、XLPicture および XLMarker が追加されました。

画像は次の方法で作成できます

  XLPicture pic = new XLPicture
  {
    NoChangeAspect = true,
    NoMove = true,
    NoResize = true,
    ImageStream = fIn,
    Name = "Test Image"
  };

現在のところ、ファイルではなくストリームのみを受け入れ、JPEG のみを吐き出します。要望があれば変更可能です。

写真が作成されたら、その場所のマーカーを作成します

  XLMarker fMark = new XLMarker
  {
    ColumnId = 2,
    RowId = 2
  };
  pic.AddMarker(fMark);

単一のマーカーを追加すると、画像がセルに直接埋め込まれます。2 つのマーカーを追加すると、画像は 2 つのマーカーにまたがります。

次に、それをシートに追加するだけです

 worksheet.AddPicture(pic);

乾杯。

于 2015-07-08T13:22:25.880 に答える
2

この機能は、バージョン 0.89.0 からクローズド XML に含まれています。

このコードは MVC5 用ですが、他の場所でも使用できます。

        public ActionResult Contact()
    {
        //Creating excelsheet and adding workbook with name Picture
        XLWorkbook workbook = new XLWorkbook();
        IXLWorksheet worksheet = workbook.Worksheets.Add("Picture");

        //Adjusting size of the excel cell as per requirement
        worksheet.Column(3).Width = 60;
        worksheet.Row(3).Height = 50;

        var imagePath = @"~/Images/Picture2.png";

        //Adding image to the worksheet and moving it to the cell
        var image = worksheet.AddPicture(Server.MapPath(imagePath))
            .MoveTo(worksheet.Cell(3, 3).Address);
        image.Name = "Logo";

        //Scaling down image as per our cell size
        image.ScaleWidth(.5);
        image.ScaleHeight(.3);

        //Formating the cell with border and color
        worksheet.Cell(3, 3).Style.Border.OutsideBorder = XLBorderStyleValues.Thick;
        worksheet.Cell(3, 3).Style.Border.OutsideBorderColor = XLColor.Blue;

        //asving worksheet in memory stream
        MemoryStream stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        //returning the final excelsheet with name Picture
        return new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        { FileDownloadName = "Pictures.xlsx" };
    }

詳細な説明については、リンクを参照してください。それが誰かに役立つことを願っています

https://www.youtube.com/watch?v=8X0kg0YzI2g&t=242s

于 2018-10-29T08:39:29.590 に答える