本篇文章将介绍如何通过控件Spire.XLS for .NET更改Excel图表中的字体及格式。包括更改图表标题、图例、坐标轴、坐标轴标题、图表数据标签等字体。可应用格式包括字体、字号、颜色、粗细、倾斜等。
测试文档
C#
//实例化Workbook类的对象,并加载测试文档
Workbook workbook = new Workbook();
workbook.LoadFromFile("test.xlsx");
//获取工作表中的第一个图表
Worksheet ws = workbook.Worksheets[0];
Spire.Xls.Chart chart = ws.Charts[0];
//更改图例字体、字号、字体颜色、字体粗细等
ExcelFont font = workbook.CreateFont();
font.Size = 10.0;
font.Color = Color.Brown;
font.IsBold = true;
font.FontName = "幼圆";
//应用字体设置到图例
chart.Legend.TextArea.SetFont(font);
//应用字体设置到图表数据标签
foreach (ChartSerie cs in chart.Series)
{
cs.DataPoints.DefaultDataPoint.DataLabels.TextArea.SetFont(font);
}
//更改坐标轴标题名称及格式
//横轴
chart.PrimaryCategoryAxis.Title = "月 份";
chart.PrimaryCategoryAxis.TitleArea.Font.FontName = "幼圆";
chart.PrimaryCategoryAxis.TitleArea.Font.IsBold = true;
//纵轴
chart.PrimaryValueAxis.Title = "销 售 额";
chart.PrimaryValueAxis.TitleArea.Font.FontName = "幼圆";
chart.PrimaryValueAxis.TitleArea.Font.IsBold = true;
//更改坐标轴字体格式
//横轴
chart.PrimaryCategoryAxis.Font.Color = Color.BlueViolet;
chart.PrimaryCategoryAxis.Font.IsBold = true;
chart.PrimaryCategoryAxis.Font.FontName = "幼圆";
//纵轴
chart.PrimaryValueAxis.Font.Color = Color.BlueViolet;
chart.PrimaryValueAxis.Font.IsBold = true;
chart.PrimaryValueAxis.Font.FontName = "幼圆";
//更改图表标题名称
chart.ChartTitle = "1季度销售额";
//保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010);
VB.NET
'实例化Workbook类的对象,并加载测试文档
Dim workbook As New Workbook()
workbook.LoadFromFile("test.xlsx")
'获取工作表中的第一个图表
Dim ws As Worksheet = workbook.Worksheets(0)
Dim chart As Spire.Xls.Chart = ws.Charts(0)
'更改图例字体、字号、字体颜色、字体粗细等
Dim font As ExcelFont = workbook.CreateFont()
font.Size = 10.0
font.Color = Color.Brown
font.IsBold = True
font.FontName = "幼圆"
'应用字体设置到图例
chart.Legend.TextArea.SetFont(font)
'应用字体设置到图表数据标签
For Each cs As ChartSerie In chart.Series
cs.DataPoints.DefaultDataPoint.DataLabels.TextArea.SetFont(font)
Next
'更改坐标轴标题名称及格式
'横轴
chart.PrimaryCategoryAxis.Title = "月 份"
chart.PrimaryCategoryAxis.TitleArea.Font.FontName = "幼圆"
chart.PrimaryCategoryAxis.TitleArea.Font.IsBold = True
'纵轴
chart.PrimaryValueAxis.Title = "销 售 额"
chart.PrimaryValueAxis.TitleArea.Font.FontName = "幼圆"
chart.PrimaryValueAxis.TitleArea.Font.IsBold = True
'更改坐标轴字体格式
'横轴
chart.PrimaryCategoryAxis.Font.Color = Color.BlueViolet
chart.PrimaryCategoryAxis.Font.IsBold = True
chart.PrimaryCategoryAxis.Font.FontName = "幼圆"
'纵轴
chart.PrimaryValueAxis.Font.Color = Color.BlueViolet
chart.PrimaryValueAxis.Font.IsBold = True
chart.PrimaryValueAxis.Font.FontName = "幼圆"
'更改图表标题名称
chart.ChartTitle = "1季度销售额"
'保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010)
结果文档