News Category

This article will show you how to replace the searched text with image in Excel worksheet by using Spire.XLS in Java applications.

Sample Excel:

Java replace the text with image in Excel worksheet

import com.spire.xls.*;
import java.io.IOException;

public class replaceTextwithImage {
    public static void main(String[] args) throws IOException {

        //Load the sample Excel document
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");
        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Find the text string {{Image}}
        CellRange[] ranges = worksheet.findAllString("{{Image}}", false, false);
        for (CellRange range : ranges) {
            //set the text as null
            range.setText("");

            //get the row and column of the searched range
            int row = range.getRow();
            int column = range.getColumn();
            //Add the image to the searched range
            worksheet.getPictures().add(row, column, "logo.jpg", ImageFormatType.Jpeg);

            //Save the document to file
            workbook.saveToFile("replaceTextwithImage.xlsx", ExcelVersion.Version2013);
            }
        }
    }

Output:

Java replace the text with image in Excel worksheet

Spire.XLS for Java supports to insert Word, Excel, PowerPoint slide and PDF as linked object or embedded object into Excel Worksheet. This article will show you how to insert a Word document as an embedded object into Excel by using Spire.XLS for Java in Java applications.

import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import com.spire.doc.*;
import com.spire.doc.documents.ImageType;
import java.awt.image.BufferedImage;

public class insertOLEObjects {
    public static void main(String[] args) {
        String docFile = "Sample.docx";
        String outputFile = "output/insertOLEObjects_result.xlsx";

        //Load the Excel document
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");
        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Generate image
        BufferedImage image = GenerateImage(docFile);
        //insert OLE object
        IOleObject oleObject = worksheet.getOleObjects().add(docFile, image, OleLinkType.Embed);
        oleObject.setLocation(worksheet.getCellRange("B4"));
        oleObject.setObjectType(OleObjectType.ExcelWorksheet);
        //Save the file
        workbook.saveToFile(outputFile, ExcelVersion.Version2010);
    }

    private static BufferedImage GenerateImage(String fileName) {

        //Load the sample word document
        Document document = new Document();
        document.loadFromFile(fileName);

        //Save the first page of word as an image
        BufferedImage image = document.saveToImages(0, ImageType.Bitmap);
        return image;
    }
}

Output:

Insert OLE Object in Excel in Java applications

This article will demonstrate how to insert and remove shapes in Excel file using Spire.XLS for Java.

Add shapes to Excel worksheet:

import com.spire.xls.*;
import com.spire.xls.core.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class addShapestoExcel {
    public static void main(String[] args) throws Exception {

        String output = "output/AddShapesToExcelSheet.xlsx";

        //create a workbook.
        Workbook workbook = new Workbook();

        //get the first worksheet.
        Worksheet sheet = workbook.getWorksheets().get(0);

        //add a triangle shape.
        IPrstGeomShape triangle = sheet.getPrstGeomShapes().addPrstGeomShape(2, 2, 100, 100, PrstGeomShapeType.Triangle);
        //fill the triangle with solid color.
        triangle.getFill().setForeColor( Color.YELLOW);
        triangle.getFill().setFillType( ShapeFillType.SolidColor);

        //add a heart shape.
        IPrstGeomShape heart = sheet.getPrstGeomShapes().addPrstGeomShape(2, 5, 100, 100, PrstGeomShapeType.Heart);
        //fill the heart with gradient color.
        heart.getFill().setForeColor(Color.RED);
        heart.getFill().setFillType(ShapeFillType.Gradient);

        //add an arrow shape with default color.
        IPrstGeomShape arrow = sheet.getPrstGeomShapes().addPrstGeomShape(10, 2, 100, 100, PrstGeomShapeType.CurvedRightArrow);

        //add a cloud shape.
        IPrstGeomShape cloud = sheet.getPrstGeomShapes().addPrstGeomShape(10, 5, 100, 100, PrstGeomShapeType.Cloud);
        //fill the cloud with custom picture
        BufferedImage image = ImageIO.read(new File("SpireXls.png"));
        cloud.getFill().customPicture(image, "SpireXls.png");
        cloud.getFill().setFillType( ShapeFillType.Picture);

        //save to file.
        workbook.saveToFile(output, ExcelVersion.Version2013);
        }
}

Output:

Insert and remove shapes in Excel in Java

Remove a particular shape or all shapes from Excel worksheet:

import com.spire.xls.*;

public class removeShape {
    public static void main(String[] args) throws Exception {

                 //Load the sample file
                Workbook workbook = new Workbook();
                workbook.loadFromFile("output/AddShapesToExcelSheet.xlsx");

                //get the first worksheet.
                Worksheet sheet = workbook.getWorksheets().get(0);

                //delete the second shape in the worksheet
                sheet.getPrstGeomShapes().get(1).remove();

              /* //delete all shapes in the worksheet
                for (int i = sheet.getPrstGeomShapes().getCount()-1; i >= 0; i--)
                 {
                   sheet.getPrstGeomShapes().get(i).remove();
                 }*/

                //save to file.
                workbook.saveToFile("output/RemoveParticularShape.xlsx", ExcelVersion.Version2013);
            }
        }

Effective screenshot after remove the second shape from Excel worksheet:

Insert and remove shapes in Excel in Java

A digital signature is an electronic signature with encrypted information that helps verify the authenticity of messages, software and digital documents. They are commonly used in software distribution, financial transactions, contract management software, and other situations that require forgery or tampering detection. When generating an Excel report, you may need to add a digital signature to make it look more authentic and official. In this article, you will learn how to add or delete digital signatures in Excel in Java using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>14.4.1</version>
    </dependency>
</dependencies>
    

Add a Digital Signature to Excel in Java

You can add a digital signature to protect the integrity of an Excel file. Once the digital signature is added, the file becomes read-only to discourage further editing. If someone makes changes to the file, the digital signature will become invalid immediately.

Spire.XLS for Java provides the addDigitalSignature method of Workbook class to add digital signatures to an Excel file. The detailed steps are as follows:

  • Instantiate a Workbook instance.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Instantiate a CertificateAndPrivateKey instance with the specified certificate (.pfx) file path and the password of the .pfx file.
  • Add a digital signature to the file using Workbook.addDigitalSignature(CertificateAndPrivateKey, String, Date) method.
  • Save the result file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.digital.CertificateAndPrivateKey;

import java.util.Date;

public class AddDigitalSignature {
    public static void main(String []args) throws Exception {
        //Create a Workbook instance
        Workbook workbook=new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Add a digital signature to the file
        CertificateAndPrivateKey cap = new CertificateAndPrivateKey("Test.pfx","e-iceblue");
        workbook.addDigitalSignature(cap, "e-iceblue",new Date());

        //Save the result file
        workbook.saveToFile("AddDigitalSignature.xlsx", ExcelVersion.Version2013);
    }
}

Java: Add or Delete Digital Signatures in Excel

Delete Digital Signature from Excel in Java

Spire.XLS for Java provides the removeAllDigitalSignatures method of Workbook class for developers to remove digital signatures from an Excel file. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Remove all digital signatures from the file using Workbook.removeAllDigitalSignatures() method.
  • Save the result file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;

public class DeleteDigitalSignature {
    public static void main(String []args) throws Exception {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("AddDigitalSignature.xlsx");

        //Remove all digital signatures in the file
        workbook.removeAllDigitalSignatures();

        //Save the result file
        workbook.saveToFile("RemoveDigitalSignature.xlsx", ExcelVersion.Version2013);
    }
}

Java: Add or Delete Digital Signatures in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article will demonstrate how to use Spire.XLS for Java to remove the formulas but keep the values on the Excel worksheet.

Firstly, view the original Excel:

Java remove the formulas but keep the values on Excel worksheet

import com.spire.xls.*;

public class Test {
    public static void main(String[] args) throws Exception {

        String inputFile = "Sample.xlsx";
        String outputFile="output/removeFormulasButKeepValues_result.xlsx";

        //Create a workbook.
        Workbook workbook = new Workbook();
        //Load the file from disk.
        workbook.loadFromFile(inputFile);
        //Loop through worksheets.
        for (Worksheet sheet : (Iterable) workbook.getWorksheets())
        {
            //Loop through cells.
            for (CellRange cell : (Iterable) sheet.getRange())
            {
                //If the cell contains formula, get the formula value, clear cell content, and then fill the formula value into the cell.
                if (cell.hasFormula())
                {
                    Object value = cell.getFormulaValue();
                    cell.clear(ExcelClearOptions.ClearContent);
                    cell.setValue(value.toString());
                }
            }
        }
        //Save to file
        workbook.saveToFile(outputFile, ExcelVersion.Version2013);
    }
}

Output:

Java remove the formulas but keep the values on Excel worksheet

Splitting a worksheet can be beneficial when you have a large amount of data and want to organize it into separate files for easier management and sharing. By using this approach, you can organize and distribute your data in a more organized and structured manner. In this tutorial, we will demonstrate how to split a worksheet into multiple Excel documents by using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>14.4.1</version>
    </dependency>
</dependencies>
    

Split a Worksheet into Several Excel Files

Spire.XLS for Java provides powerful features that enable us to achieve this task efficiently. The specific steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel file using Workbook.loadFromFile() method.
  • Get the specific sheet using Workbook.getWorksheets().get() method.
  • Get the header row and cell ranges using Worksheet.getCellRange() method.
  • Create a new workbook and copy the header row and range 1 to the new workbook using Worksheet.copy(CellRange sourceRange, Worksheet worksheet, int destRow, int destColumn, boolean copyStyle, boolean updateRerence) method.
  • Copy the column width from the original workbook to the new workbook using Workbook.getWorksheets().get(0).setColumnWidth() method.
  • Save the new workbook to an Excel file using Workbook.saveToFile() method.
  • Repeat the above operation to copy the header row and range 2 to another new workbook, and save it to another Excel file.
  • Java
import com.spire.xls.CellRange;
        import com.spire.xls.ExcelVersion;
        import com.spire.xls.Workbook;
        import com.spire.xls.Worksheet;

public class SplitWorksheet {

    public static void main(String[] args) {

        //Create a Workbook object to load the original Excel document
        Workbook bookOriginal = new Workbook();
        bookOriginal.loadFromFile("C:\\Users\\Administrator\\Desktop\\Emplyees.xlsx");

        //Get the first worksheet
        Worksheet sheet = bookOriginal.getWorksheets().get(0);

        //Get the header row
        CellRange headerRow = sheet.getCellRange(1, 1, 1, 5);

        //Get two cell ranges
        CellRange range1 = sheet.getCellRange(2, 1, 6, 5);
        CellRange range2 = sheet.getCellRange(7, 1, 11, 5);

        //Create a new workbook
        Workbook newBook1 = new Workbook();

        //Copy the header row and range 1 to the new workbook
        sheet.copy(headerRow, newBook1.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range1, newBook1.getWorksheets().get(0), 2, 1, true, false);

        //Copy the column width from the original workbook to the new workbook
        for (int i = 0; i < sheet.getLastColumn(); i++) {
            newBook1.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }

        //Save the new workbook to an Excel file
        newBook1.saveToFile("Sales.xlsx", ExcelVersion.Version2016);

        //Create another new workbook
        Workbook newBook2 = new Workbook();

        //Copy the header row and range 2 to the new workbook
        sheet.copy(headerRow, newBook2.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range2, newBook2.getWorksheets().get(0), 2, 1, true, false);

        //Copy the column width from the original workbook to another new workbook
        for (int i = 0; i < sheet.getLastColumn(); i++) {
            newBook2.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }

        //Save it to another new Excel file
        newBook2.saveToFile("Technicians.xlsx", ExcelVersion.Version2016);
    }
}

Java: Split a Worksheet into Several Excel Files

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article demonstrates how to split a worksheet into several Excel documents by using Spire.XLS for Java.

import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class SplitWorksheet {

    public static void main(String[] args) {

        //Create a Workbook object to load the original Excel document
        Workbook bookOriginal = new Workbook();
        bookOriginal.loadFromFile("C:\\Users\\Administrator\\Desktop\\Emplyees.xlsx");

        //Get the first worksheet
        Worksheet sheet = bookOriginal.getWorksheets().get(0);

        //Get the header row
        CellRange headerRow = sheet.getCellRange(1, 1, 1, 5);

        //Get two cell ranges
        CellRange range1 = sheet.getCellRange(2, 1, 6, 5);
        CellRange range2 = sheet.getCellRange(7, 1, 11, 5);

        //Create a new workbook
        Workbook newBook1 = new Workbook();

        //Copy the header row and range 1 to the new workbook
        sheet.copy(headerRow, newBook1.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range1, newBook1.getWorksheets().get(0), 2, 1, true, false);

        //Copy the column width from the original workbook to the new workbook
        for (int i = 0; i < sheet.getLastColumn(); i++) {

            newBook1.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }

        //Save the new workbook to an Excel file
        newBook1.saveToFile("Sales.xlsx", ExcelVersion.Version2016);

        //Copy the header row and range 2 to another workbook, and save it to another Excel file
        Workbook newBook2 = new Workbook();
        sheet.copy(headerRow, newBook2.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range2, newBook2.getWorksheets().get(0), 2, 1, true, false);
        for (int i = 0; i < sheet.getLastColumn(); i++) {

            newBook2.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }
        newBook2.saveToFile("Technicians.xlsx", ExcelVersion.Version2016);
    }
}

Split a Worksheet into Several Excel Files in Java

This article demonstrates how to add Trendline to an Excel chart and read the equation of the Trendline using Spire.XLS for Java.

Add Trendline

import com.spire.xls.*;
import com.spire.xls.core.IChartTrendLine;

import java.awt.*;

public class AddTrendline {
    public static void main(String[] args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("test.xlsx");

        //Get the first chart in the first worksheet
        Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);

        //Add a Trendline to the first series of the chart
        IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().add(TrendLineType.Linear);

        //Set Trendline name
        trendLine.setName("Linear(Series1)");
        //Set line type and color
        trendLine.getBorder().setPattern(ChartLinePatternType.DashDot);
        trendLine.getBorder().setColor(Color.blue);
        //Set forward and backward value
        trendLine.setForward(0.5);
        trendLine.setBackward(0.5);
        //Set intercept value
        trendLine.setIntercept(5);

        //Display equation on chart
        trendLine.setDisplayEquation(true);
        //Display R-Squared value on chart
        trendLine.setDisplayRSquared(true);

        //Save the result file
        workbook.saveToFile("AddTrendline.xlsx", ExcelVersion.Version2013);
    }
}

Add Trendline to Chart and Read Trendline Equation in Excel in Java

Read Trendline equation

import com.spire.xls.Chart;
import com.spire.xls.Workbook;
import com.spire.xls.core.IChartTrendLine;

public class ReadEquationOfTrendline {
    public static void main(String[] args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("AddTrendline.xlsx");

        //Get the first chart in the first worksheet
        Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);

        //Read the equation of the first series of the chart
        IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().get(0);
        String equation = trendLine.getFormula();
        System.out.println("The equation is: " + equation);
    }
}

Add Trendline to Chart and Read Trendline Equation in Excel in Java

This tutorial will demonstrate how to set font and background color for Excel textbox using Spire.XLS for Java.

The following is a screenshot of a sample document:

Set Font and Background Color for Excel Textbox in Java

Using the code

import java.awt.*;
import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.shapes.*;

public class SetFontAndBackground {
    public static void main(String[] args) {
        //Load an Excel sample
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Get the textbox which will be edited
        XlsTextBoxShape shape = (XlsTextBoxShape) sheet.getTextBoxes().get(0);

        //Set the font and background color for the textbox
        //Set font
        ExcelFont font = workbook.createFont();
        font.setFontName("Calibri");
        font.setSize(14);
        font.isBold(false);
        font.setColor(Color.MAGENTA);
        (new RichText(shape.getRichText())).setFont(0, shape.getText().length() - 1, font);

        //Set background color
        shape.getFill().setFillType(ShapeFillType.SolidColor);
        shape.getFill().setForeKnownColor(ExcelColors.Yellow);

        //Save to file
        workbook.saveToFile("output/setFontAndBackgroundForTextBox.xlsx", ExcelVersion.Version2013);
    }
}

Output

Set Font and Background Color for Excel Textbox in Java

This article demonstrates how to set Excel page margins before printing the Excel worksheets in Java applications. By using Spire.XLS for Java, we could set top margin, bottom margin, left margin, right margin, header margin, and footer margin. Please note that the unit for margin is inch on Spire.XLS for Java while On Microsoft Excel, it is cm (1 inch=2.54 cm).

import com.spire.xls.*;

public class setMargins {
    public static void main(String[] args) {

        String outputFile="output/setMarginsOfExcel.xlsx";

        //Load the sample document from file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx";);

        //Get the first worksheet.
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Get the PageSetup object of the first worksheet.
        PageSetup pageSetup = sheet.getPageSetup();

        //Set the page margins of bottom, left, right and top.
        pageSetup.setBottomMargin(2);
        pageSetup.setLeftMargin(1);
        pageSetup.setRightMargin(1);
        pageSetup.setTopMargin(3);
        
        //Set the margins of header and footer.
        pageSetup.setHeaderMarginInch(2);
        pageSetup.setFooterMarginInch(2);

        //Save to file.
        workbook.saveToFile(outputFile, ExcelVersion.Version2013);

    }
}

Output:

Java set Excel print page margins

Page 4 of 9