At some point, you may want to use multiple
fonts and font colors for outstanding some specific words in one Excel cell. In
this article, I’m going to show you how to use multiple fonts and font colors
in one Excel cell programmatically in Java by using Free Spire.XLS for Java
API.
Before
using the following code, you need to download Free
Spire.XLS for Java API, unzip
the package and then add Spire.Xls.jar in the lib folder into your project. If
you’re creating maven projects, you can install Free Spire.XLS for Java API
from maven
repository.
Using the code
import com.spire.xls.*;
import java.awt.*;
public class UseMultipleFontsAndFontColors {
public static void main(String[]
args) throws Exception {
//Create a Workbook instance
Workbook wb = new Workbook();
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Create one Excel font
ExcelFont font1 = wb.createFont();
font1.setFontName("Calibri");
//Set font color
font1.setColor(Color.blue);
font1.setSize(12f);
font1.isBold(true);
//Create another Excel font
ExcelFont font2 = wb.createFont();
font2.setFontName("Times New Roman");
//Set font color
font2.setColor(Color.red);
font2.setSize(12f);
font2.isBold(true);
//Insert text to cell B5
RichText richText = sheet.getCellRange("B5").getRichText();
richText.setText("Blue and Read");
//Apply two fonts to the text in the cell B5
richText.setFont(0, 3, font1);
richText.setFont(9, 12, font2);
//Save the document
wb.saveToFile("MultipleFonts.xlsx", ExcelVersion.Version2013);
}
}
Output:
Comments
Post a Comment