Search code examples
c#.netoffice-interopcom-interopexcel-interop

Problem trying to add title to Charts in ChartSheets using Excel Interop with Visual C#


I'm trying to make ChartSheets in Excel from a datasheet; I managed to make the charts, but some of the charts don't change style and are title-less. This is the code that makes the charts and uses the ChartWizard to change their format:

Excel.Chart[] GráficasFrecuenciaGanancia = new Excel.Chart[numberOfTables];

            //Para trabajar con cada gráfica.
            for (int i = 1; i <= numberOfTables; i++)
            {
                GráficasFrecuenciaGanancia[i - 1] = currentWorkbook.Charts.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Colocamos una hoja de trabajo para gráficas y la asignamos al objeto.
                               
                if (GráficasFrecuenciaGanancia[i-1] == null)
                {
                    MessageBox.Show("Error", "Null found");                    
                }                          
                

                GráficasFrecuenciaGanancia[i - 1].ChartWizard(
                    Gallery: XlChartType.xlLineMarkers,
                    PlotBy: XlRowCol.xlColumns,
                    CategoryLabels: 45,
                    SeriesLabels: 5,
                    HasLegend: true,
                    Title: allTheCells.Item[1 + ((i - 1) * 54), 1].Value2,
                    CategoryTitle: "Frecuencias (Hz)",
                    ValueTitle: "Ganancias (dB)",
                    ExtraTitle: "Extra"
                    );   

Then, I decided to change their style manually (and it worked), but changing the title gives an exception; the exception happens when it tries to change the title of GráficasFrecuenciaGanancia[13].

GráficasFrecuenciaGanancia[i - 1].ChartType = XlChartType.xlLineMarkers;
                GráficasFrecuenciaGanancia[i-1].HasTitle = true;
                Excel.ChartTitle TítuloGráfica = null;
                TítuloGráfica = GráficasFrecuenciaGanancia[i - 1].ChartTitle;
                TítuloGráfica.Text = allTheCells.Item[1 + ((i - 1) * 54), 1].Value2; //This is the line that gives the exception.

This is the exception: (0x80004005 (E_FAIL))" - System.Runtime.InteropServices.COMException

It is weird, because the line that gives the exception doesn't cause any problem with the previous charts, and I also delete all the charts before running the code.


Solution

  • Just for the record, I solved the issue trimming the string, the string was 260 characters long, and it had a lot of escape characters (tabs, returns and new lines). It seems like there is a limit to the characters that can be assigned to the .Text property, I don't know if the limit is in characters or in points, but that's how I solved the issue.