Asp Excel integration: open/close xls files on server – read/write cell

This is a particular scenario: I have to use an excel worksheet as calculation engine on a web page. MS itself discourages the asp-excel (application) integration but this is the easiest method I found. Here are my test’s steps and the code for the test, in asp:

  • Create an Excel Object and open a worksheet of an xls file;
  • 1
    2
    3
    4
    5
    
    Set ex = server.CreateObject("Excel.Application")
    If IsObject(ex) Then
    ex.Application.DisplayAlerts = False
    ex.Application.Visible= True
    ex.Workbooks.Open("C:\Inetpub\wwwroot\testExcel\Test.xls")
  • Write a pair of values on two cells (I prepared a third cell with the SUM formula for these two cells, to test the formulas execution);
  • 6
    7
    
    ex.ActiveSheet.Cells(1,1).Value = "4"
    ex.ActiveSheet.Cells(1,2).Value = "3"
  • Save (that means execution of the formulas, the file Test1.xls is only for cache, the real file saved is the same Test.xls) and close the file and Excel Application;
  • 8
    9
    10
    11
    12
    13
    
    ex.Save("C:\Inetpub\wwwroot\testExcel\Temp1.xls")
    ex.Workbooks.Close
    ex.Quit
    Else
    Response.write("Can Not Connect to Excel.Application")
    End IF
  • Reopen the xls file, as first point;
  • Read the cell of the formula result;
  • 1
    
    Response.write(ex.ActiveSheet.Cells(4,4).Value)
  • close the file and Excel Application, as before;

The great limitation of the solution is that Excel must be installed on the web server.

Share this post:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Buzz
  • LinkedIn
  • Tumblr
Posted giovedì, settembre 23rd, 2010 under Web Development.

Leave a Reply