Domanda

How to create and set styles in Excel cells using C#?

I want to write something like "April 1st" with st as a superscript. I would be using a string format not a date format.

I have tried http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx but getting an The name 'Globals' does not exist in the current context error. I have added assembly Microsoft.Office.Interlop.Excel. Am I missing any other assembly?

Excel.Style style = Globals.ThisWorkbook.Styles.Add("NewStyle");
È stato utile?

Soluzione

You actually don't want to change the font of the whole cell but you to change a portion of the text in the cell I take it. You'll still need to retrieve the cell range and then adjust the characters within that range. here is an example where it's just adjusting the first cell. A1.

If you wanted to change the whole cell range to be superscript it would be done like this currentRange.Font.Superscript = true;

void Main()
{
         var app = new Application();
        app.Visible = true;
        var workbook = app.Workbooks.Add(1);

        Sheets excelSheets = workbook.Worksheets;
        string currentSheet = "Sheet1";
        Worksheet worksheet1 = (Worksheet)excelSheets.get_Item(currentSheet);

        worksheet1.Cells[1, 1] = "April 1st";
        worksheet1.Cells[1, 2] = "April 2nd";
        worksheet1.Cells[1, 3] = "April 3rd";
        worksheet1.Cells[1, 4] = "April 4th";

        // fill in the starting and ending range programmatically this is just an example. 
        string startRange = "A1";
        string endRange = "A1";
        Range currentRange = worksheet1.get_Range(startRange , endRange );

        var text = currentRange.Text.ToString();
        int length = text.Length;
        int index = 0;
        if(text.Contains("st"))
        {
            index =text.IndexOf("st");
        }
        //The other checks for "nd", "rd", "th" obviously check to see a # precedes these.

        if(index > 0)
        {           
            currentRange.get_Characters( index+1, 2).Font.Superscript  = true;              
        }           
}

Altri suggerimenti

As the MSDN article you've linked to states:

Applies to: The information in this topic applies to document-level projects and application-level projects for Office 2013 and Office 2010. See Features Available by Office Application and Project Type.

To use Globals class you have to create Office project. For another reference you can check this question about creating Office add-in:

Globals.ThisAddin.Application can be only used in VSTO Add-In

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top