Click here to Skip to main content
15,885,435 members
Articles / Productivity Apps and Services / Microsoft Office / Microsoft Excel
Tip/Trick

Excel Interop, Subscripts and Superscripts

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
17 Aug 2017CPOL 9.1K   89   4  
A demo that generates a simple Excel spreadsheet with subscripts and superscripts

Note: To run the code, you must have Excel 2010 or above and Visual Studio installed. The assembly that I reference is Microsoft.Office.Interop.Excel 14.0.

Introduction

From time to time, we need to put subscripts and superscripts into an Excel spreadsheet. While Unicode does support subscripts and superscripts (in plain text format) for some characters, many characters are not supported. This demo will show you how to format characters in Excel as subscripts and superscripts.

Using the Code

Download and unzip the file attached, open ExcelDemo.cs, go to method PopulateTable, you will find this:

C#
private void PopulateTable(Excel.Worksheet sheet)
{
    Excel.Range cell1 = sheet.Cells[1, 1];
    Excel.Range cell2 = sheet.Cells[1, 2];
    cell1.Value = "Time (s)";
    cell2.Value = "vball1 (m/s)";
    cell2.Characters[2, 4].Font.Subscript = true;
    cell2.Characters[6, 1].Font.Superscript = true;

For a cell in an excel spreadsheet, you may select the characters that you want to format, and set them as subscripts or superscripts.

Similarly, you may also format a chart like this (check method AddChart):

C#
// Format yAxis
var yAxis = (Excel.Axis)chart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
yAxis.HasTitle = true;
yAxis.AxisTitle.Text = "vball (m/s)";
yAxis.AxisTitle.Characters.Font.Size = 12;
yAxis.AxisTitle.Characters[2, 4].Font.Subscript = true;

Results:

Image 1

History

  • Version 1.0. August 17, 2017

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --