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

Display MS Excel Sheets and Charts in ASPX Pages using C#

By , 8 Nov 2006
 

Introduction

The purpose of this article is to show how to display the exact values in an Excel sheet, with its comments, in an aspx page. The code-behind file is in C#. The method shown here helps to display an Excel sheet with its formatting including the font, color, alignment etc. This will be very useful for developers who do MS Office automation. The pre-requisites are that in the DCOM CONFIG your Excel application should be given permissions to be accessed and loaded in the server system.

Sample Image - ExcelShtAndChrt-In-aspx.jpg

Conversion of the Excel formats require only a few lines of code. The format details include conversion of Excel attributes to .NET attributes, like Excel color to .NET Color.

/// <SUMMARY>
/// Converts Excel Color to Dot Net Color
/// </SUMMARY>
/// Excel Object Color
/// <RETURNS>Returns System.Drawing.Color</RETURNS>
private System.Drawing.Color 
        ConvertExcelColor2DotNetColor(object objExcelColor)
{

    string strColor = "";
    uint uColor = 0;
    int nRed = 0;
    int nGreen = 0;
    int nBlue = 0;

    strColor = objExcelColor.ToString();
    uColor = checked((uint)Convert.ToUInt32(strColor));
    strColor = String.Format("{0:x2}", uColor);
    strColor = "000000" + strColor;
    strColor = strColor.Substring((strColor.Length - 6), 6);

    uColor = 0;
    uColor = Convert.ToUInt32(strColor.Substring(4, 2), 16);
    nRed = (int)uColor;

    uColor = 0;
    uColor = Convert.ToUInt32(strColor.Substring(2, 2), 16);
    nGreen = (int)uColor;

    uColor = 0;
    uColor = Convert.ToUInt32(strColor.Substring(0, 2), 16);
    nBlue = (int)uColor;

    return System.Drawing.Color.FromArgb(nRed, nGreen, nBlue);
}

The format details also include conversion of Excel horizontal alignment to .NET horizontal alignment:

/// <SUMMARY>
/// Converts Excel Horizontal Alignment to DotNet Horizontal Alignment
/// </SUMMARY>
/// Excel Horizontal Alignment
/// <RETURNS>HorizontalAlign</RETURNS>
private HorizontalAlign ExcelHAlign2DotNetHAlign(object objExcelAlign)
{
    switch (((Excel.Range)objExcelAlign).HorizontalAlignment.ToString())
    {
        case "-4131":
            return HorizontalAlign.Left;
        case "-4108":
            return HorizontalAlign.Center;
        case "-4152":
            return HorizontalAlign.Right;
        default:
            return HorizontalAlign.Left;
    }
}

Next is the conversion of Excel vertical alignment to .NET vertical alignment:

/// <SUMMARY>
/// Converts Excel Vertical Alignment to DotNet Vertical Alignment
/// </SUMMARY>
/// Excel Vertical Alignment
/// <RETURNS>VerticalAlign</RETURNS>
private VerticalAlign ExcelVAlign2DotNetVAlign(object objExcelAlign)
{
    switch (((Excel.Range)objExcelAlign).VerticalAlignment.ToString())
    {
        case "-4160":
            return VerticalAlign.Top;
        case "-4108":
            return VerticalAlign.Middle;
        case "-4107":
            return VerticalAlign.Bottom;
        default:
            return VerticalAlign.Bottom;
    }

}

Chart View

Sample Image - ExcelShtAndChrt-In-aspx.jpg

The selection of sheet name will be displayed by "*" delimited. This is because "*" cannot be accepted in Worksheet names.

Problems faced in displaying a Worksheet

  1. Merging of rows is not included because it needs to find out the logic of combining rows (whereas columns merge is possible on insertion as a TableRow).
  2. The chart object is a GIF file, it is generated and put in the server and displayed in an ASPX page. (Here, there is no need to get the chart object inside the page). This is a preliminary trial to put a chart on an ASPX page.

Forthcoming Plans

To display all types of MS Office files in ASPX pages and to produce intelligence on data values etc.

Points to Consider

This meets the business requirements with data display alone and no activities processed. A template of Excel with cell references to other Excel files will give a real time stylesheet data report.

Summary

This page will be enhanced by including several functionalities of MS Excel.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Gnanandam Gopalan
Web Developer
India India
Member
I am basically a C++ Programer done various project for Industrial Automation Activities.

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   
QuestionProblem occured !!!!!!!memberzimzamzim20 Sep '11 - 1:04 
after selecting the List button following error occurs
 
System.Runtime.InteropServices.COMException (0x800A03EC): 'PopulationSample.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct. If you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted. at Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad) at ExcelSheetDisplay.GetListofSheetsAndCharts(String strFileName, Boolean bReadOnly, DropDownList drpList) in c:\Users\sivanesan\Desktop\New folder\ExcelSheetChartDisplay\ExcelSheetDisplay.aspx.cs:line 131
 
Please suggest me a right solution ..
 
Note: i have tried permission concept but not acceptingConfused | :confused:
Regards
Shiva

AnswerRe: Problem occured !!!!!!!membermatrixology27 Nov '11 - 18:14 
Same problem with me Confused | :confused:
GeneralNo display for imagememberMember 778553224 May '11 - 4:51 
I compiled and ran the code. I proceeded to select the PopulationSample ->List ->Chart0-14 Population Chart. The graphical image does not appear, however there is a small icon instead. I used the 2010 Visual studio and 2007 Office
Thank you in advance for advice
Regards,
KJ
GeneralOld format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))memberNuclearStorm16 Feb '11 - 4:26 
I tried all solutions you given but still have this Exception
 

 
System.Runtime.InteropServices.COMException (0x80028018): Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)) at Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad) at ExcelSheetDisplay.GetListofSheetsAndCharts(String strFileName, Boolean bReadOnly, DropDownList drpList) in d:\ExcelSheetChartDisplay\ExcelSheetDisplay.aspx.cs:line 124
GeneralImage in excel is not Displayingmemberam7429 Mar '10 - 21:36 
Hi
If in a excelsheet contains some images(i.e. logo) is not displaying in aspx page.
Please help how could i resolve it.
anjan maity

GeneralProblem in Displaying ExcelmemberPallaviwakde5 Feb '10 - 0:06 
Hello,
This code is very useful for me.
But when my web app is hosted on Windows server 2008 . I could not see the excel file.
I have done the DCOMCNFG settings for NETWORK SERVICE account.
I am getting following error:
 
System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'C:\Websites\PMT-Dev\TempFiles\gpblanke_Five Panel Report-(02-05-2010).xls'. There are several possible reasons: • The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the same name as a currently open workbook. at Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad) at ExcelSheetDisplay.GetListofSheetsAndCharts(String strFileName, Boolean bReadOnly, DropDownList drpList) in C:\Websites\PMT-Dev\ExcelSheetDisplay.aspx.vb:line 157
 
Any help woul be greatly appreciated!!
Thanks in advance
 

-Pallavi
GeneralRe: Problem in Displaying Excelmembersnpcrud20 Dec '10 - 9:44 
Am also having the same problem. Have setup the application in IIS7 on local PC. Has anyone got a solution to this problem?
 
Thanks
GeneralRe: Problem in Displaying Excelmembersnpcrud20 Dec '10 - 10:11 
Don't worry. found the solution. You need to created a directory called 'Desktop' under C:\Windows\SysWOW64\config\systemprofile. Solved my issue anyway.
GeneralRe: Problem in Displaying Excelmembermatrixology27 Nov '11 - 18:25 
tried your method. but of no avail. Unsure | :~
GeneralRe: Problem in Displaying Excelmembersnpcrud28 Nov '11 - 9:59 
Hi matrixology,
 
Gave up on Office automation tools, could not install MS Office COM components on the webserver. Just wanted to read an Excel file in the end and used EPPLus - more info here -> http://epplus.codeplex.com/documentation. Simple to pull data from an Excel file and manipulate.
 
Cheers
GeneralRe: Problem in Displaying Excelmembermatrixology28 Nov '11 - 17:04 
thanks buddy...the link was great
GeneralNeed same code for VB.NetmemberAnOnYmOuS_S24 Nov '09 - 2:18 
Its really nice application.Will you please provide same script for apsx page but with VB.Net
GeneralCool applicationmemberLulama8 Mar '09 - 21:55 
When I grow up I want to create applications like this one Smile | :)
GeneralNice Applicationmemberatheequepasha12 Nov '08 - 18:14 
Really Nice App. Thank you. I was looking for a tool like this.
Do you have any idea how i can take the data and convert into graph without having the chart created in excel file.
 
Thanks for your Help
Atheeque Smile | :)
Generaltemp gif filememberMember 391781022 Sep '08 - 5:24 
I tried using this example and I get an exception when it tries to export the c:\tempgif.gif file. I don't have this file. Am I supposed to create it myself or was it supposed to be included in the zip source.
 
Harvey
GeneralLoading takes a long timememberAgnes Loyola16 Jul '08 - 3:29 
Hi
The excel Sheet takes a very long time to load.Can anyone help me to reduce the time to load the Excel Sheet.
GeneralDisplay Excel inside the aspx pagememberAgnes Loyola11 Jul '08 - 20:56 
on a button click event i Redirect the aspx1 page to another aspx2 page in the server, where the aspx2 opens an excel sheet.The code used in aspx2 Page Load event(which is in the server) is
 string fliepath = "http://servername/xyz.xls";
      string filename = System.IO.Path.GetFileName(fliepath);
      string path = Path.GetDirectoryName(fliepath);
        Response.Clear();
        Response.ClearHeaders();
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("Content-Disposition", "attachment; filename="+filename);
        Response.Flush();
        Response.WriteFile(@"D:\foldername\xyz.xls");    
        Response.End();  
This works fine.i am able to open and save the file.But i want the Excel to open inside the aspx1 page as you done here(Excel inside the panel).As am new to asp.net am not able to understand the codings given here.Can you make something simple to achieve my task.Please.....
GeneralTo display excel sheetmemberAgnes Loyola11 Jul '08 - 1:24 
string fliepath = "http://xyz/vv.xls";
string filename = System.IO.Path.GetFileName(fliepath);
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Disposition", "attachment; filename="+filename);
Response.Flush();
Response.WriteFile(fliepath);
Response.End();

i used this code in the Page Load inorder to open the Excel in the page Load.When i run this page i am getting an error in the line Response.WriteFile(fliepath); as http://xyz/vv.xls is not a valid virtual path.
Can anyone help me please....
AnswerRe: To display excel sheetmemberGnanandam Gopalan11 Jul '08 - 2:46 
you need to give your Inetpub path of the file say (c:\\inetpub\\wwwroot\\ProjectName\\xyz.xls)
 

This will work for loading and saving a file... Filepath is not suppose to be given here...
 
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=xyz.xls");
Response.Charset = "utf-8";
StringWriter sw = new StringWriter();
sw.Append("My Data");
Response.Write(sw.ToString());
Response.End();
 
Cheers, Gnanandam
 
Generic Thoughts under Pressure Environments

GeneralRe: To display excel sheetmemberAgnes Loyola11 Jul '08 - 3:06 
Thank you so much for the Information.
Questionhow to load the Excel sheet in the page loadmemberAgnes Loyola10 Jul '08 - 1:05 
used the same code as given here.it works fine. thanks a lot.
Can anyone help me to load the excel sheet in the page load instead of clicking butons.Please....
AnswerRe: how to load the Excel sheet in the page loadmemberGnanandam Gopalan10 Jul '08 - 1:14 
Thanks for your comments.. Instead you can do the same in Page Load Event...
 
Cheers, Gnanandam
 
Generic Thoughts under Pressure Environments

GeneralThanks for nice Example, But I am getting one errors [modified]memberMember 204885626 Feb '08 - 20:50 
System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC at Excel._Chart.Export(String Filename, Object FilterName, Object Interactive)
 
In Dcom config I checked LAUNCH and ACTIVATION for both remote and local to asp.net_machinename account.
 
This error I am getting when I try to run it from IIS 5 (I creat virtual directory gave read and write permisions), I am using Windows Xp Pro SP2 , office 2003 and vs 2005 .
 
If I am running it from VS development environment I have no issues running perfectly.
 
Then I did one change I added ASPNET user account to Administrator group and restart my pc and it works fine but as soon as I remove aspnet acount from admin group and restart it give me same error message.
 
pkhussin
 
modified on Wednesday, February 27, 2008 3:36 AM

GeneralNicememberPooya Musavi19 Oct '07 - 8:00 
Hi
greate article,but may you help me how i can add visio shapes
to my windows forms using C#?
I want add some shapes programmatically.
Thanks
GeneralRe: NicememberGnanandam Gopalan21 Oct '07 - 23:11 
Thnx 4 ur comments.. I will try the same and let you know about it.. I think it will not be a problem once if you insert as an object in Microsoft Excel.
 
Cheers, G
 
Generic Thoughts under Pressure Environments

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 9 Nov 2006
Article Copyright 2006 by Gnanandam Gopalan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid