Document Solutions for Excel, Java Edition | Document Solutions
Features / Worksheet / Range Operations / Set Cell Background Image for Cell Range
In This Topic
    Set Cell Background Image for Cell Range
    In This Topic

    DsExcel enables you to set the cell background image and its layout for the cell range using setBackgroundImage and setBackgroundImageLayout methods in IRange interface. You can only export the cell background image to PDF, HTML, and IMG and can only view it in SpreadJS when saved in .sjs format. BackgroundImageLayout enumeration allows you to set the background image layout to Stretch (default), Center, Zoom, or None.

    DsExcel only supports and exports the following image formats as the cell background image:

    Refer to the following example code to add a cell background image in different layouts and export the workbook to a PDF file:

    Java
    Copy Code
    // Create a new workbook.
    Workbook workbook = new Workbook();
    
    IWorksheet worksheet = workbook.getWorksheets().get(0);
    
    // Load the image.
    InputStream stream = new FileInputStream("Chrome_icon.png");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int bytesRead;
    while (true) {
        try {
            if (!((bytesRead = stream.read(buffer)) != -1)) break;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        outputStream.write(buffer, 0, bytesRead);
    }
    byte[] imagebyte = outputStream.toByteArray();
    
    worksheet.getRange("A2:E2").setValue(new String[] { "Stretch", "Center", "Zoom", "None", "Default(Stretch)" });
    worksheet.getRange("A3:E3").setValue("Chrome");
    worksheet.getRange("A3:E3").setRowHeightInPixel(80);
    worksheet.getRange("A3:E3").setColumnWidthInPixel(100);
            
    // Add cell background image.
    worksheet.getRange("A3:E3").setBackgroundImage(imagebyte);
    
    // Set image layout.
    worksheet.getRange("A3").setBackgroundImageLayout(BackgroundImageLayout.Stretch);
    worksheet.getRange("B3").setBackgroundImageLayout(BackgroundImageLayout.Center);
    worksheet.getRange("C3").setBackgroundImageLayout(BackgroundImageLayout.Zoom);
    worksheet.getRange("D3").setBackgroundImageLayout(BackgroundImageLayout.None);
    
    // Set PDF export options.
    workbook.getActiveSheet().getPageSetup().setPrintGridlines(true);
    workbook.getActiveSheet().getPageSetup().setPrintHeadings(true);
        
    // Save to a PDF file.
    workbook.save("CellBackgroundImage.pdf");

    Limitations

    DsExcel does not support saving the background image to Excel; hence, you cannot view it in Excel.