Export to Office

November 04, 2004 12:11 AM
DevConnections
Rating: (0)

Control Freak

LANGUAGES:VB.NET | HTML

ASP.NETVERSIONS: 1.0 | 1.1

 

Export to Office

Export Web Content to Excel, Word, PowerPoint, and evenWordPerfect

 

 

There?s just no doubt about it ? people love their Webbrowsers. However, that doesn?t mean they don?t appreciate their otherapplications, too. Like it or not, Microsoft Office is pretty much the standardfor most business tasks.

 

Sturdy and capable, Office applications can manipulatedata in ways that Web browsers cannot. Happily, your users can have the best ofboth worlds; viewing data in their browser and editing it in other greatapplications. The custom Web control detailed in this article will make it easyfor you to satisfy your users in such ways.

 

The ExportPanel Control

There are a variety of ways to export Web content to suchapplications. (For more details see Exportto Excel.) HTML has been around for years now, and most modern applicationsspeak it quite fluently. This fact is central to the design strategy of theExportPanel Web control, which essentially sends simplified HTML directly tothe appropriate application.

 

By default, the control behaves exactly like a standardPanel Web control, because it inherits from the Panel Web control and thereforegets all that functionality for free. However, the ExportPanel control has afew extra properties that encapsulate the exporting functionality.

 

The first property you?re likely to notice is theExportType property. This enumeration allows the developer to pick whichapplication will be used for the export. The default is HTML, which will causethe ExportPanel to act exactly like a standard Panel control. The moreinteresting choices are Excel, Word, PowerPoint, and WordPerfect. Choosing oneof these applications will cause the content of the ExportPanel to be openedwith that application.

 

Figure 1 shows the ExportPanel being used to contain anHTML Table control that has three rows and three columns. There are a varietyof fonts and colors, with a textbox in the top-right cell. Underneath the HTML Tablecontrol is a Label control, also within the dotted borders of the ExportPanel. Belowthe ExportPanel are other controls that will not be exported to other formats. Thesecontrols allow the user to select the export format, and whether theapplication should open within the browser or externally.

 


Figure 1: Everything placed withinthe ExportPanel control (pictured here with a dotted border) will be exportedto the application that the user selects in the listbox.

 

Of course, different applications provide varying levelsof support for HTML. All the modern versions of applications supported by thiscontrol will render HTML. (Assuming your users have at least Office 2000, youshouldn?t have many problems with the output.) However, they all put their ownpersonal touches on the display of the HTML.

 

Figure 2 shows the nearly perfect results when exported toExcel, and Figure 3 shows the output when PowerPoint is chosen. The WordPerfectexport in Figure 4 is displayed beautifully, with only the textbox havingissues. The theme here is: don?t use textboxes (and other input controls likeButtons and DropDownLists), or you?re asking for formatting problems. Therefore,you?ll have better success by exporting read-only data reports with controlslike DataGrids, Labels, Tables, and other basic HTML. It really doesn?t makesense to have input controls in your exports anyway, because these applicationsdon?t support postbacks. Image controls work nicely, although they?ll work mostconsistently if you set the ImageURL property to an absolute URL rather than arelative one.

 


Figure 2: Excel exports work well,with only the textbox having slight crowding problems.

 


Figure 3: This PowerPoint slideshowof the export results show that textboxes are not supported, but hyperlinkswork flawlessly.

 


Figure 4: WordPerfect output is,well, perfect! (Although you should avoid textboxes and other input controls toprevent related display issues.)

 

How It Works

Figure 5 shows the basic template used for theconstruction of the ExportPanel custom Web control. If you?ve been followingthis column, this code should look quite familiar. After importing some commonnamespaces and establishing some basic toolbox support, the class is declaredto inherit from the Panel control.

 

Imports System.ComponentModel

Imports System.Web.UI

 

<ToolboxData("<{0}:ExportPanel runat=server>"_

+ "</{0}:ExportPanel>")> _

Public Class ExportPanel

 InheritsSystem.Web.UI.WebControls.Panel

 

 'TODO: Properties

 

 'TODO: Methods

End Class

Figure 5: Everycustom Web control starts with a template very similar to this.

 

Figure 6 lists the definitions for the public propertiesof the ExportPanel control, and a public enum named AppType. The ExportTypeproperty encapsulates a private variable named m_ExportType, which is of typeAppType. The attributes specify that the ExportType property will be bindable,and will be displayed in the Behavior section of the property window when beingused at design time.

 

'Contains the list of supported export applications

Public Enum AppType

 HTML

 Word

 Excel

 PowerPoint

 WordPerfect

End Enum

 

'Manage the requested export type

Private m_ExportType As AppType

<Bindable(True), Category("Behavior")> _

Public Property ExportType() As AppType

 Get

     Return m_ExportType

 End Get

 

 Set(ByVal Value AsAppType)

     m_ExportType = Value

 End Set

End Property

 

'Filename property

Dim m_FileName As String = "File1"

<Bindable(True), Category("Appearance"), _

 DefaultValue("File1")> _

Public Property FileName() As String

 Get

     Return m_FileName

 End Get

 

 Set(ByVal Value AsString)

     m_FileName = Value

 End Set

End Property

 

'Open the application externally or host in the browser?

Private m_OpenInBrowser As Boolean = True

<Bindable(True),Category("Behavior"),DefaultValue("True")>_

Public Property OpenInBrowser() As Boolean

 Get

     If ExportType =AppType.WordPerfect Then

         'WordPerfect can'tbe hosted inside IE

         Return False

     Else

         If ExportType =AppType.HTML Then

             'HTML willalways be displayed

             'on thecurrent page.

             Return True

         Else

             Returnm_OpenInBrowser

         End If

     End If

 End Get

 

 Set(ByVal Value AsBoolean)

     m_OpenInBrowser =Value

 End Set

End Property

Figure 6: TheAppType enum is used by the ExportType property to list and control theapplications supported for export. FileName is a fairly standard stringproperty, and OpenInBrowser is a Boolean property that handles a couple ofspecial cases.

 

FileName is a fairly standard string whose job is to holdthe file name that will be given to the application handling the export. Thefinal property (named OpenInBrowser) controls whether the application will behosted inside the browser or not. Because WordPerfect can?t be hosted insideInternet Explorer, the property will always return False when this ExportTypeis chosen. Additionally, the HTML ExportType signifies that the control will bedisplayed as a standard panel in the current page, so it returns True in thiscase.

 

Finally, the Panel control?s Render method is overridden,as shown in Figure 7. This is where all the real work is done. As mentionedpreviously, if the HTML ExportType is selected, the control should act as astandard Panel control. The easiest way to accomplish this is to have theunderlying Panel control do its usual rendering, so MyBase.Render is called todo all the work. Otherwise, some fancy rendering will be necessary.

 

Protected Overrides Sub Render(ByVal output As _

System.Web.UI.HtmlTextWriter)

 If ExportType =AppType.HTML Then

   MyBase.Render(output)

 Else

  'Get rid of all the junkthat's been

  'rendered to the page sofar

  Page.Response.Clear()

 

  'Start a very simplehtml document

  Page.Response.Write("<html><head></head><body>")

 

  'Determine whether toopen the document inside

  'the browser or to anlaunch external app

  Dim OpenType As String ="inline"

  If OpenInBrowser = FalseThen OpenType = "attachment"

 

  'Determine the contenttype and file extension

  Dim FileExtension AsString

  With Page.Response

    Select Case ExportType

      Case AppType.Excel

        .ContentType ="application/ms-excel"

        FileExtension =".xls"

      Case AppType.Word

        .ContentType ="application/ms-word"

        FileExtension =".doc"

      CaseAppType.Powerpoint

        .ContentType ="application/ms-powerpoint"

        FileExtension =".ppt"

      CaseAppType.WordPerfect

        .ContentType ="application/wordperfect9"

        FileExtension =".wpd"

    End Select

  End With

 

  'Build full filenamewith extension (if necessary)

  Dim FullFileName AsString = FileName.Trim().ToLower

  If NotFullFileName.EndsWith(FileExtension) Then

    FullFileName +=FileExtension

  End If

 

  'Output the HTML header

  Page.Response.AddHeader("Content-Disposition", _

    OpenType +";filename=" + FullFileName)

 

  'Output the contents ofthe panel

  MyBase.RenderChildren(output)

 

  'End the HTML document

  Page.Response.Write("</body></html>")

  Page.Response.End()

 End If

End Sub

Figure 7: TheRender method is where all the real work is done. A very basic HTML page is renderedand handed off to the requested application.

 

Customized Rendering

By the time the Render method of the ExportPanel isexecuted, the Page_Load event has already been called and ASP.NET hasautomatically added a bunch of headers and ViewState junk that will onlyconfuse the applications that are about to receive the output from this page. (Also,other controls may be on the page outside the borders of the ExportPanel, andthese should not be exported.) Therefore, it is best to simplify things so theresulting HTML is as basic as possible, resulting in more standard rendering nomatter which application is used. So everything dumped into the Page so far iscleared, and only the most basic HTML elements are added to begin the new page.

 

Next, a final check is done to determine whether theapplication will be opened within the browser or not. The string ?inline? or ?attachment?will be added to a header further along in the code. This is what tells thebrowser how to open the resulting document.

 

The Select Case block in the center of the methoddetermines the ContentType that many browsers require, as well as the fileextension, which is also usually necessary for the browser to interpret thetype of application required to open the document. The next code block simplyensures the file name actually ends up using that file extension.

 

Next, a header is output to the Page?s Response stream. Thisheader gives the browser the file name and gives it the final request to openthe application within the document or not.

 

After all that preparation, the contents of theExportPanel are finally ready to be added to the output stream. It only takes asingle line of code to do all that work, by calling the RenderChildren methodof the base Panel object.

 

To wrap things up, the closing tags of this basic HTMLpage are rendered, and the Response is ended to help ensure no other controlson the page are exported besides the ones inside the ExportPanel.

 

Design-time Details

After all the preceding code has been put into a Webcontrol library project, it can be compiled into a DLL and added to the VisualStudio.NET toolbox. Then it can be dropped onto a Web form in any ASP.NET Webapplication and used just like any other control in the toolbox.

 

Drag the ExportPanel onto a Web form, size it to theheight and width of your liking, and fill it with stuff. As mentioned earlier,input controls don?t tend to work well in the resulting exports, so stick withstandard reporting output such as grids, labels, and other static text. My experimentationshave also suggested that setting the Web form?s PageLayout property toFlowLayout tends to display better results than the default GridLayout.

 

You can set any of the standard Panel properties to makeit look nice if you wish to use it as a standard Panel. Then, by setting theExportType property (either at design time or run time) it will spring to life,providing seamless exporting capabilities to your data presentations. As theresulting file arrives in the browser, a dialog box will be presented to theuser asking if they wish to save or open the file. This browser securityfeature cannot be disabled via ASP.NET.

 

In essence, it all boils down to setting the appropriatecontent type, specifying the file name, and requesting that the application beopened either inside the browser or externally. It also helps to simplify theHTML so the various applications will be able to display the resulting fileeasily and consistently.

 

The ExportPanelcontrol and source code referenced in this article are available for download.

 

Steve C. Orr is anMCSD and a Microsoft MVP in ASP.NET. He?s been developing software solutionsfor leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about it, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://Steve.Orr.netor e-mail him at mailto:Steve@Orr.net.

 

Advanced Solutions from Third-parties

HTML is not the only technique available for exporting to Officeapplications, and sometimes more control is needed than HTML can provide. Perhapsyou want to output several sheets to Excel and have them all appropriatelynamed, and maybe throw some fancy formulas and charts in there, too. These aresome of the many potential requirements that HTML output is not likely to meet.If you need advanced exporting functionality, here are two quality third-partyproducts that just might earn their keep: