使用 OpenXML 将背景图像添加到 Excel [英] Add background image to Excel using OpenXML

查看:106
本文介绍了使用 OpenXML 将背景图像添加到 Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Open XML 创建 Excel.我想将背景图像添加到 Excel.不要告诉我将图像添加到 excel 并与 OpenXML Productivity Tool 进行比较.请让我知道提取方式来做到这一点?

I'm using Open XML to create Excel. I want to add background image to the Excel. Don't tell me add image to excel and compare with OpenXML Productivity Tool. Please let me know extract way to do this?

推荐答案

我已经深入研究了如何使用 OpenXML 将背景图像应用到 Excel,并且正在共享代码.

I have dig into applying a background image to Excel using OpenXML and I am sharing code.

class Program
{
    static void Main(string[] args)
    {
        //pathe of the Excel file to add background image
        string document = @"Book1.xlsx";
        // Open the document for editing.  
        using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(document, true))
        {
            //  Get existing sheets from workbook.  
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
            // Loop through all sheets and add image as background
            foreach (var sheet in sheets.Elements<Sheet>())
            {
                WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);
                CreateWorksheetPart(worksheetPart);
            }
        }
    }

    public static void CreateWorksheetPart(WorksheetPart part)
    {
        ImagePart imagePart1 = part.ImageParts.FirstOrDefault();
        if (imagePart1 == null)
            imagePart1 = part.AddNewPart<ImagePart>("image/jpeg", "rId1");
        string str = part.GetIdOfPart(imagePart1);
        GenerateImagePart1Content(imagePart1);
        GeneratePartContent(part, str);

    }
    private static void GenerateImagePart1Content(ImagePart imagePart1)
    {
        using (var stream = new FileStream("WatermarkDoc.png", FileMode.Open))
        {
            imagePart1.FeedData(stream);
        }
    }

    private static void GeneratePartContent(WorksheetPart part, string idPart)
    {
        Worksheet worksheet1 = part.Worksheet;
        Picture picture1 = new Picture() { Id = idPart };
        worksheet1.Append(picture1);
    }
}

使用以下工具查找 openXML 中的更多类.https://www.microsoft.com/en-us/下载/details.aspx?id=30425?

Use the below tool to find out more classes in openXML. https://www.microsoft.com/en-us/download/details.aspx?id=30425?

这篇关于使用 OpenXML 将背景图像添加到 Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆