Click here to Skip to main content
Click here to Skip to main content

Excel Charts in C# Applications

By , 1 Aug 2007
 

Introduction

If you want to create advanced graphics and charts in C# applications, you can create them using C# and GDI+, or by using third-party graphics and chart packages. However, you can achieve this goal by taking advantage of Microsoft Excel's built-in chart features directly in C# applications.

Microsoft Visual Studio .NET makes it possible for you to create rich Microsoft Excel-based applications based on the C# Framework. You can take advantage of all of the functionality provided by Excel's large object models in C# applications. In this article, I will show you how to use the surface charts in your C# applications.

Background

In order for Excel to be used in C# applications, we need to resolve the issue of interoperation between C# and Excel. Excel application can be regarded as a COM server, so the basis of interoperation between C# and Excel applications is COM Interop. The .NET Framework provides good support for interaction with COM components. To use Excel COM components in a C# project, you simply need to add this COM component to reference. This can be done by right clicking the project in the Solution Explorer and selecting Add Reference. Click the COM tab and select the appropriate type of Object library depending on the version of Microsoft Office you are using: 

  • Office 97: Microsoft Excel 8.0 Object Library
  • Office 2000: Microsoft Excel 9.0 Object Library
  • Office XP: Microsoft Excel 10.0 Object Library
  • Office 2003: Microsoft Excel 11.0 Object Library

After this step, you should find that references have been added for the Office Core and Excel as well. In my case, I built my project using Visual Studio .NET 2005 and Microsoft Office XP. So my reference to Excel is Microsoft Excel 10.0 Object Library.

Next, I will use the surface chart as an example to demonstrate how to involve Excel in a C# application. In this example, I will create a Windows Form application with two buttons on Form1. One button is used to start Plot, and the other to quit Excel and close Form1. Clicking the Plot button will launch Excel, add a new workbook to the collection of workbooks, get Active Sheet, and put data into Excel cells, and draw the surface chart.

Excel surface charts display multiple-series data on a surface using the category axis, value axis, and a third axis that displays the series name. Surface charts are used to show the optimum combination of category and series data.

Using the Code

The project is implemented in a single Form1 class. In this class, we first create data using a 1D and 2D array and assign them to the Excel worksheet. This data must be structured in a certain format. The categories (used as the X axis) are in the first column. The second row represents the series names (used as the Y axis). Finally, the data values are formed by a 2D data array.

As long as the data is assigned to the Excel worksheet, you can create a surface chart by selecting the surface chart type:

xlChart.ChartType = XlChartType.xlSurface; 

The rest of the code in the Form1 class is used to customize the axes, add axis labels and a title, and remove the legend from the chart.

This project produces the output of Figure 1. It can be seen that the chart is created by ranges of data values, which is evident by the fact that the colors vary with the values along the vertical (the Z) axis. The number of colors on the surface chart is based on the major unit of the Z axis.

Figure 1: Excel surface chart created in a C# application.

The Excel surface chart has four subtypes:

  1. xlSurface: Displays a standard surface chart
  2. xlSurfaceWireFrame: Displays a surface chart without colors
  3. xlSurfaceTopView: Displays the a surface chart viewed from above
  4. xlSurfaceTopViewWireFrame: Displays a surface chart without colors, viewed from above

You can select a different subtype of surface chart from the above four options according to your application requirements.

I should point out here that Excel surface charts have some limits: they are not true X-Y-Z charts. X and Y are not treated as numeric data, and must consist of regularly defined, evenly spaced categories. Exactly one Z value is needed for each X-Y pair. Excel surface charts are drawn by connecting Z values at X-Y nodes with straight lines and planar sections. A saddle point is not accurately drawn if it occurs between the X-Y nodes. Color-filled surface charts in Excel do not allow transparency, meaning that you cannot visualize the hidden parts of the surface.

This project is from the examples of Chapter 9 of my new book "Practical C# Charts and Graphics", where you can find more advanced chart and graphics programming for real-world .NET applications. For more information, please visit my Web site.

About the Author

Dr. Jack Xu has a Ph.D in theoretical physics. He has over 15 years programming experience in Basic, Fortran, C, C++, Matlab, and C#, specializing in numerical computation methods, algorithms, physical modeling, computer-aided design (CAD) development, graphics user interface, and 3D graphics. Currently, he is responsible for developing commercial CAD tools based on Microsoft .NET Framework.

Please also read my other articles:

License

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

About the Author

Jack J. H. Xu
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberfreegoods8 Dec '12 - 22:11 
The code is very useful. Best wishes to the author.
QuestionSystem.BadImageFormatException was unhandledmemberayyangar1 Aug '12 - 13:26 
System.BadImageFormatException was unhandled
Could not load file or assembly 'Interop.Excel, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
 
the programs builds fine, but i cant run it.
please help
ayyangar
Aug 1
AnswerRe: System.BadImageFormatException was unhandledmemberfreegoods8 Dec '12 - 22:06 
It seems that you are using a version of Excel that is different from the one described in the article.
 
If you have Microsoft Office 2010 installed:
1. Remove "Excel" and "Office" references.
2. Add the new COM reference to "Microsoft Excel 14.0 Object Library".
3. Update (From1.cs)
using Excel;
to
using Microsoft.Office.Interop.Excel;
4. Update (From1.cs, Lines 9, 14)
Excel.Application
to
Microsoft.Office.Interop.Excel.Application
 
Now it should work well.
QuestionUpdate for Office Excel 2010, VS 2010memberasalzber9 May '12 - 17:38 
This sample will almost run as is in Office 2010. To make it work, remove office assemblies and add Microsoft.Office.Interop.Excel.
 
Then substitute the usings from Excel with
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
 
and add "Excel." to every unrecognized object. Everything else works as expected.
GeneralMy vote of 5membermanoj kumar choubey20 Feb '12 - 20:36 
Nice
QuestionHow to Make Bold in Part of an Excel Cell - Need Eargent help!!!!!!!membersupuna2u12 Sep '10 - 17:13 
HI,
Any body knows how to bold a part of a excel cell content with c# coding? eg: abcdefgh if so plz send a email to supuna2u@gmail.com or post the answer here. This is a big help! I have googled but could not came up with a solution
 
Thank you
Generalscrollbarmembereng.jeblak4 Aug '10 - 2:03 
it is great article
 
thanksfor sharing;
 
but how can add scrollbar to the chart when i have huge data.
 
thanks in advance
Generalseememberaxinkumar18 Feb '10 - 22:06 
Confused | :confused: Cool | :cool: Cool | :cool:
GeneralInterOp Excel Charts in ASP.NET ApplicationmemberKarthi.CSC18 Dec '09 - 2:38 
Hi Jack & All,
 
Is there any way to incorporate the InterOp library in an ASP.NET Application..
 
Thanks in advance..
 
Regards,
Karthikeyan
GeneralGood Stuff!memberebrewste14 Sep '09 - 13:58 
Thanks so much! This was so much more help than the official help pages from Microsoft.
GeneralWith Open XML Format SDK 2.0 you can generate charts in open format, this is really great toolmemberMaciej Gren21 Aug '09 - 8:18 
Hi,
thank you for your article. Since the time it was written, there are other tools existing for Microsoft Developers, for instance Open XML SDK 2.0 which enables you to create Excel, Power Point and other files in few minutes. You can also load already existing ones to reflector and generate C# code for later purpose. Really great. Especially if you want to make complex and customized charts. Firstly you are creating it using Excel. Then you put this file into Reflector and as a result you have customizable code.Here is described how you can build your own Excel file using this SDK
QuestionReference COM: Excell, Office, VBIDEmemberColdSun1 Jul '09 - 18:45 
When I open project. Project couldn't reference to Excell, Office or VBIDE com. I tried reference files in bin\debug\ folder but when run, it get exception:
"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Example9_7.exe
 
Additional information: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154"
 
How to solve it? Need install Com? If need, how to install?
(My computer don't install MS Office).
Thanks and best regards,
ColdSun.
GeneralRe: Reference COM: Excell, Office, VBIDE [modified]memberzoonny14 Mar '12 - 16:33 
I added reference.
 
Microsoft.Office.Core
Microsoft.Office.Interop.Excel
Microsoft.Office.Tools.Common(C:\Program Files\Reference Assemblies\Microsoft\VSTO\v8.0)
Microsoft.Office.Tools.Excel(C:\Program Files\Reference Assemblies\Microsoft\VSTO\v8.0)

 
and removed reference.
Excel
Office

 
and added namespace
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

 
My System Environment
Visual Studio 2008
Microsoft Office 2010


modified 15 Mar '12 - 2:46.

GeneralThanks a lot!membertenyears11 May '09 - 17:59 
Thank you very much for sharing the great code!
QuestionHow not to displau any values on Category axis (Horizontal axis)membervblearn26 Aug '08 - 10:31 
Hi,
 
I am plotting the excel chart using vb.net. I don't want to display any value on the horizontal axis. Any one know how to do it?
 
thanks
--girija
GeneralUsing VS2003, .Net Framework 2memberMeDev18 Feb '08 - 3:01 
Hi,
 
I'm trying to run it under VS2003, .Net Framework 1.4 but the application doesn't succeed to open the Excel.
 
When I'm running it on the VS2005, it's working great but I need it to run on the earlier version (it's not in my hands).
 
thanks,
- Me.
GeneralRe: Using VS2003, .Net Framework 2membertenyears11 May '09 - 18:10 
Hello
Maybe we have the same problem of the sample,but if you just want to see the running result of the code,you can copy the contents of "btnPlot_Click" and "AddData" to your project.I copied them and they're working well now.Good luck to U!Thumbs Up | :thumbsup:
GeneralExcel ReferencememberDrati18 Dec '07 - 1:36 
Hi
 
I'm kind of a newbie on this. The Excel i'm using is the 2003 version so, i've tried to change the reference by removing the original and adding the
"Microsoft Excel 11.0 Object Library". The problem, when i try to build the app, is i get the error "The type or namespace name 'Excel' could not be found (are you missing a using directive or an assembly reference?)"
 
i'm lost over here, if someone could help me i would apreciate it.
 
thanks
GeneralRe: Excel ReferencememberMeDev18 Feb '08 - 2:57 
try to add the "using Excel;" in the beginning of the page.
 
good luck.
GeneralRe: Excel Referencemembervirdigs18 Apr '10 - 22:54 
insted...... try using "Microsoft Excel 5.0 Object Library".
GeneralNicememberPooya Musavi19 Oct '07 - 8:04 
Hi
Great article,may you help me how i can add Visio shapes
to my Windos Form using C#?
I want to add some shapes programmatically and want to have them
with sth written inside dynamically and also with connector shape?
Thanks a lot

QuestionI have an exception running your ApplicationmemberKnight's Scent19 Aug '07 - 22:23 
When I try to run your application I have a System.Runtime.InteropServices.COMException saying Old format or invalid type library. (Exception from HRESULT : 0x80028018 (TYPE_E_INVDATEREAD)
can u help me with that please?
 
Knight's Scent

AnswerRe: I have an exception running your ApplicationmembertalosDk4 Oct '07 - 7:03 
hey
i got the same problem, but i found some help here
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=384846&SiteID=1[^]
 
the bug are in excel,
try this

System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//call Excel method here
System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;
 
thx to Sven De Bont

GeneralYour other articlememberaxelriet20 Jul '07 - 17:32 
Hello,
 
I cannot find another article of yours titled "Creating Stock Charts Using C#" that you posted last June. Was it removed?
 
Cheers,
Axel
GeneralRe: Your other articlememberJack J. H. Xu1 Aug '07 - 14:17 
you can find it on my website at
 
http://authors.unicadpublish.com/~jack_xu/stock_chart.html
 
jack
 
Dr. Jack Xu has a Ph.D in theoretical physics. He has over 15 years programming experience in Basic, FORTRAN, C, C++, Matlab, and C#.

GeneralDisplay the chart directly on the WinForm!memberPatric_J29 Mar '07 - 14:02 
Here's how to use the chart control directly on the WinForm instead of opening Excel:
 
Using MSChart from a C# WinForm
 
/Patric
My C# blog: C# Coach

GeneralRe: Display the chart directly on the WinForm!memberJack JH Xu30 Mar '07 - 4:57 
I also present a method to display Excel chart directly on the Win Form in my book.
 
Jack
 
Dr. Jack Xu has a Ph.D in theoretical physics. He has over 15 years programming experience in Basic, FORTRAN, C, C++, Matlab, and C#.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 1 Aug 2007
Article Copyright 2007 by Jack J. H. Xu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid