在Microsoft Excel中,我们可以通过设置单元格格式来设置Excel的字体,实现对Excel 字体,字形,字号,下划线,颜色及删除线,上下标等特殊效果的设置。Spire.XLS提供ExcelFont 对象让程序员可以很简单的完成对Excel单元格里的字体进行设置。
本文将详细描述如何使用Spire.XLS设置Excel字体和设置Excel上标和下标。
C#
{
//实例化一个Workbook并获取第一个工作表
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
//创建字体
ExcelFont font1 = workbook.CreateFont();
//设置字体,字形,大小,颜色
font1.FontName = "宋体";
font1.IsBold = true;
font1.Size = 10;
font1.KnownColor = ExcelColors.Blue;
//为A1单元格写入数据并设置字体
RichText richText = sheet.Range["A1"].RichText;
richText.Text = "Excel字体设置";
richText.SetFont(0, richText.Text.ToArray().Length - 1, font1);
//设置Excel上标
ExcelFont font2 = workbook.CreateFont();
font2.IsSuperscript = true;
RichText richText2 = sheet.Range["A2"].RichText;
richText2.Text = "A2+B2=C2";
richText2.SetFont(1, 1, font2);
richText2.SetFont(4, 4, font2);
richText2.SetFont(7, 7, font2);
//设置Excel下标
ExcelFont font3 = workbook.CreateFont();
font3.IsSubscript = true;
RichText richText3 = sheet.Range["A3"].RichText;
richText3.Text = "H2O";
richText3.SetFont(1, 1, font3);
//保存文档
workbook.SaveToFile("result.xlsx",FileFormat.Version2010);
}
VB.NET
'实例化一个Workbook并获取第一个工作表
Dim workbook As New Workbook()
Dim sheet As Worksheet = workbook.Worksheets(0)
'创建字体
Dim font1 As ExcelFont = workbook.CreateFont()
'设置字体,字形,大小,颜色
font1.FontName = "宋体"
font1.IsBold = True
font1.Size = 10
font1.KnownColor = ExcelColors.Blue
'为A1单元格写入数据并设置字体
Dim richText As RichText = sheet.Range("A1").RichText
richText.Text = "Excel字体设置"
richText.SetFont(0, richText.Text.ToArray().Length - 1, font1)
'设置Excel上标
Dim font2 As ExcelFont = workbook.CreateFont()
font2.IsSuperscript = True
Dim richText2 As RichText = sheet.Range("A2").RichText
richText2.Text = "A2+B2=C2"
richText2.SetFont(1, 1, font2)
richText2.SetFont(4, 4, font2)
richText2.SetFont(7, 7, font2)
'设置Excel下标
Dim font3 As ExcelFont = workbook.CreateFont()
font3.IsSubscript = True
Dim richText3 As RichText = sheet.Range("A3").RichText
richText3.Text = "H2O"
richText3.SetFont(1, 1, font3)
'保存文档
workbook.SaveToFile("result.xlsx", FileFormat.Version2010)