Export to Excel

TreeGrid documentation

Export of grid data to MS Excel in xlsx or xhtml format, to csv, or any other format.
For IE9 and older IE versions it requires communication with server.
Other browsers can save the exported file directly or can send it also to server.

The xlsx export and direct saving without server access was added in 12.1 version.

In TreeGrid export menu it is possible to choose which columns or rows to export and set various export options.
See Configuration menu for basic settings or Export menu for special settings.

Changes for client export can be done also by <Media><M Media='Export' ... /><Media>.

Export types

Client export
The exported data are created on client and saved as xlsx or csv file directly to disk.
Or the data can be sent to server for validation and returned back to client. In IE9 and older it is the only way.
It is done by TreeGrid and does not need too much to set it up.

Server export
To server is sent only configuration in XML or JSON and server generated the data and sends them back to client.
It is done by custom server script that must be written by developers using TreeGrid.
There can be used also TreeGrid.dll/so as support library to generate the exported data on server side.
Server export is often required for server paging and server child paging to avoid loading all data to client.

Basic settings

Basic definition of export to MS Excel XLSX, XLS, CSV or any other custom type. It is for both client export or server export.
new 6.0 chg 12.1 <Cfg> string

ExportFormat

["xlsx"] Saved to cookies, avoid it by <Cfg ExportLap='1'/>
If and in which predefined format the export will be done. Case insensitive.
It is also file extension to save the report by, always lowercase.
Since 12.1 the values completely changed and replaced Export_Type.
Possible values: empty - no export, xlsx - (original binary Excel xlsx file), csv - comma or semicolon separated values, xls - (old xhtml file).
It can contain also any other value for custom export into this file format.
new 12.1 <Cfg> string

ExportName

["Export"] Saved to cookies, avoid it by <Cfg ExportLap='1'/>
File name to save the export by. It is without extension, extension is set by ExportFormat.
upd 12.1 <Cfg> string[ ]

ExportType

["Expanded,Outline"] Saved to cookies, avoid it by <Cfg ExportLap='1'/>
The way of client export (or server export via TreeGrid.dll/so) to Excel, comma separated list of keywords, case insensitive.
Many of these options can be changed in configuration menu, if set ExportCols = 2.
Since 12.1 the default value changed, Indent was replaced by Outline.
Filteredexport also filtered rows
Selected(new 12.1, xlsx / csv only) export only selected rows, columns or cells.
Expandedexport all rows expanded
Hiddenexport all columns, including hidden (Visible='0' CanExport='1'). (since 12.1, xlsx only) export also manually hidden rows (Visible='0' Hidden='1' CanExport='1').
Hide (new 12.1, xlsx), only with option Hidden Hidden columns (Visible='0') are exported as hidden. Manually hidden rows (Visible='0' Hidden='1') are exported as hidden.
Outlineexport tree as Excel outline, for csv adds new column with the outline as characters '#'
Indentindent levels in main column
FixedRows(new 12.1, xlsx only) freeze (anchor) head rows. Note, Excel does not support freezing foot rows.
FixedCols(new 12.1, xlsx only) freeze (anchor) left columns. Note, Excel does not support freezing right columns.
Empty(new 12.1, xlsx only) export empty cells as actual cells with empty string - overflowing text of preceding cells will be hidden, but the resulting xlsx file of large grids may be larger
KeepHTML(new 12.1, xlsx / csv only) places HTML tags to export, does not strip them
EnumKeys(new 12.1, xlsx only) for Enum and Radio type exports its keys, not values
TextType(new 12.1, xlsx only) preserves Text type for number values. Otherwise it converts type of number values to number type.
Unsupported(new 12.1, xlsx only) exports also TreeGrid date and number formats that are not fully supported by Excel, the unsupported part is replaced by '?'. Otherwise, if not present, exports such dates as string.
Strings(old xls only) store strings in file twice to preserve their type a spaces, set it if you want to export all strings as strings and not chosen by Excel.
Dates(old xls only) export dates as strings only (useful for exporting Hirji dates). In this case uses the <C> ExportFormat instead of XlsFormat.
Rtl(new 7.1) The columns will be exported in reversed order when the grid is in Rtl mode
new 6.0 upd 6.7 <Cfg> int

ExportCols

[2]
If and which menu will be shown before doing export.
0 - no menu
1 - menu with columns and rows to select which columns will be exported. Only columns and rows with CanExport='1' are listed.
2 - (new 6.7) menu with columns, rows and also with all options for export
See Configuration menu for basic settings or Export menu for special settings.
new 12.1 upd 13.1 <Cfg> int

ExportLoad

[0]
Set to 1 in server paging or child paging to download all rows to be exported.
Since 13.1 if set to 2 it downloads all rows also if ExportType contains flag Selected - useful if row selection is saved on server.
Be careful permitting this option, it will download all pages and optionally child pages, when used ExportType = Expanded.
new 12.1 <Cfg> int

ExportFontSize

[10]
xlsx only. Default Excel font size in every cell.
new 12.1 <Cfg> int

ExportFontFace

["Calibri"]
xlsx only. Default Excel font name in every cell.
new 12.1 <Cfg> string

ExportOptions

xlsx only. Internal options for export to xlsx. In JSON format.
HeaderColor"" Color of header rows
SelectedRowsColor"#ffff00" Color of selected rows
SelectedColsColor"#ffff00" Color of selected columns
SelectedCellsColor"#00ffff" Color of selected cells
DefaultTextShadowColor"#999999" Default TextShadowColor (RGB value)
DefaultTextShadowPattern"lightGray" Default TextShadow emulation fill pattern (lightGray = mid-dense dots)
TableBorder"1,black" Define border around the table and it's sections (head, foot, left and right columns). Set it as "width,color"
For example: ExportOptions="{TableBorder:'2,gray'}"
upd 11.0 <C> int

CanExport

[1/0]
If the column will be exported. 0 - no, 1 - yes, if chosen in menu or is visible, 2 - always
By default Panel has 0 and other columns 1.
More changes for client export can be done also by <Media><M Media='Export' ... /><Media>.
upd 12.1 <I> int

CanExport

[1]
If row will be exported to Excel.
0 - neither row, nor its children, 1 - yes, if chosen in menu or is visible, 2 - (new 11.0) only its children, 3 (new 12.1) always.
Space rows are never exported.
new 12.1 <Cfg> int

ExportVarHeight

[1]
0 - All rows are exported with single line height.
1 - Calculates height of cells in columns with VarHeight>=1, row height is set to the highest cell height. Can slow down the export!
2 - Like 1 and also ignores row MaxHeight attribute to export the whole content of all multiline cells. Can slow down the export!
new 7.0 <C> int

VarHeight

[0]
Set it to 1 (or 2) to columns containing multiline cells to let their height to calculate dynamically to export it with the whole visible content. Only with ExportVarHeight>=1.
The VarHeight attribute also controls shrinking cell height when column width is increased, see VarHeight.

Communication with server

By default (Export_Type="") the server communication is required only for IE9 and older browsers.
chg 12.1 <treegrid,bdo> string

Export_Type

[""]
If and what will be sent to server for export, case insensitive.

Client export

empty
Direct client export, default (new 12.1)
In all browsers except IE9 and below will be sent nothing to server; the generated file will be saved directly.
In IE9 and below will be sent to server full report in XLSX/CSV/XLS format (chosen by ExportFormat).

Export
Client export via server (renamed 12.1)
To server will be sent full report in XLSX/CSV/XLS format (chosen by ExportFormat).
Prior 12.1 the client export was always sent to server, using keywords "xls" or "csv"

Server export

Settings
To server will be sent only configuration (sorting, grouping, filters) and columns (positions, visibility and widths) in XML.
The server must generate the requested report in XLSX, XLS or CSV according to the settings and stored data and return it to client.
See Server export.

Expanded
Sends ids of all expanded rows in <Cfg Expanded/> attribute, comma separated.

Changes
Used usually with Settings for server export.
Sends modified rows - rows with set attribute Added, Deleted, Moved or Changed (modified values). The rows are sent in <Changes> tag.
When set, the export does not save the changes to server before export, but includes them in the export request.

This attribute supports for server export also all other settings like Cookie or Data defined for _Type, see Upload_Type. Also Export_Flags are supported if defined, see Upload_Flags.
<treegrid,bdo> string

Export_Url

If set Export_Type="" (default value), it is required only for compatibility with IE9 and older IE browsers.
Destination for page that generates data to export to XLSX, XLS, CSV or any other format.
This server URL should return the exported data as XLSX / XLS file in HTTP content-type="application/vnd.ms-excel" or CSV as "text/csv".
This communication is not done by AJAX, but always by hidden form, so it can be used even if no ActiveX is supported.
Export cannot use Soap or Get communication.
If you encounter problems with export of international (non-English) characters, add to your page, to <head> section:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

In client export (Export_Type='' or 'Export') to this URL is uploaded complete exported data and the server script should just return them back.
In server export (Export_Type='Settings' or other value) to this URL is uploaded actual grid configuration and the server script should create and return the exported data by itself.
<treegrid,bdo> string

Export_Data

["Data"]
The name of form input in that will be uploaded exported data or configuration to Export_Url.

Export API

<Actions>

Export

Attached to event OnClickButtonExport
Creates report in XLSX, XLS or CSV or a request for the server report and saves it to disk or sends it to server.
new 6.0 upd 7.0 API event bool

OnExportStart

(TGrid grid, bool pdf)
Called before the export menu is shown and the export report is generated.
(since 7.0) pdf is true for export to PDF
Return true to cancel export.
new 12.1 API event bool

OnExportInit

(TGrid grid, string[Name] Cols, string[id] Rows, object source)
Called after the options are chosen by a user in menu and before the export is generated.
Cols is array of all columns to export, by column name. If the column is not listed, it is not exported.
Rows is array of rows to export, by row id. If the row is not listed, it is exported according to its CanExport value.
It is possible to modify these arrays.
Other settings like ExportFormat or ExportType are already read from configuration and can be modified in the grid attributes.
source is data source used, can be null for direct save or grid.Source.Export for export, or grid.Source.ExportPDF for PDF export.
Can be used for custom export or export to different formats.
Return true to cancel export.
chg 12.1 API event object

OnExport

(TGrid grid, object data, int type)
Called after the export or configuration is created and before it is saved to disk or sent to server.
data is the created export or configuration. It can be string or (since 12.1) Blob object.
(since 12.1) type is data type: 0 export configuration, 1 export pdf configuration, 2 direct data to save, 3 direct data to send to server.
Return true to suppress the export.
Or return new or updated data to send.
new 12.1 API method void

SaveExport

(string data, object source = null)
Saves exported data to file (source = null) or sends it to server to source like grid.Source.Export or grid.Source.ExportPDF.
chg 12.1 API method void

SendExport

(string data, string url, string name)
Sends the data to server as export or configuration.
Since 12.1 is does not call OnExport.

Client export

By default (Export_Type="") the server communication is required only for IE9 and older browsers.

To server (to Export_Url) is sent whole prepared report that can just be returned by this page back to Excel.
The uploaded data can be plain text (for xls and csv) or base64 encoded for binary xlsx.
In "custom" parameter "ExportFormat" is sent chosen file extension "xlsx", "xls" or "csv".
In "custom" parameter "ExportName" is sent chosen file name.
Should be used only for small grids, because to server are send all data back.
Cannot be used with server paging or server child paging.
Space rows are not exported.
The server script just returns the data from Data attribute back to client with changed content type.
For MS Excel use ContentType="application/vnd.ms-excel" and charset: utf-8.

Examples of server script for client export

Point Export_Url to simple server script that will just return the received data:

ASP.NET
<%@ Page Language="C#" ContentType="application/vnd.ms-excel" %>
<% Response.AppendHeader("Content-Disposition","attachment; filename=\""+Request["ExportName"])+"."+Request["ExportFormat"]+"\"");
Response.AppendHeader("Cache-Control","max-age=1, must-revalidate");
string data = Request["Data"]; if(data==null) data = "";
if (data.IndexOf('>') >= 0 || data.IndexOf("<") >= 0 || data == "") Response.Write(HttpUtility.HtmlDecode(data));
else Response.BinaryWrite(Convert.FromBase64String(data)); %>

JSP
<%@page contentType="application/vnd.ms-excel"%><%@page pageEncoding="UTF-8"%><%
request.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition","attachment; filename=\""+request.getParameter("ExportName")+"."+request.getParameter("ExportFormat")+"\"");
response.addHeader("Cache-Control","max-age=1, must-revalidate");
String XML = request.getParameter("Data"); if(XML==null) XML = "";
if(XML.length()>0&&XML.charAt(0)=='&') XML = XML.replaceAll("<","<").replaceAll(">",">").replaceAll("&","&").replaceAll(""","\"").replaceAll("'","'");
if(XML.indexOf("<")>=0) out.print(XML);
else {
java.io.BufferedOutputStream O = new java.io.BufferedOutputStream(response.getOutputStream());
O.write(javax.xml.bind.DatatypeConverter.parseBase64Binary(XML)); O.flush(); O.close();
} %>

PHP
<?php
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=\"" . $_REQUEST["ExportName"] . "." . $_REQUEST["ExportFormat"] . "\"");
header("Cache-Control: max-age=1; must-revalidate");
$XML = get_magic_quotes_gpc() ? stripslashes($_REQUEST["Data"]) : $_REQUEST["Data"];
if(strpos($XML,"<")===false || strpos($XML,"<")===false) echo(base64_decode($XML));
else echo html_entity_decode($XML); ?>

Any other language can generate the export similarly.

Client export settings

<Cfg> string

ExportPrefix

For xlsx and csv it is text placed to the first cell.
For xls it is HTML code added into Excel report between Excel header and TreeGrid table.
<Cfg> string

ExportPostfix

For xlsx and csv it is text placed to the last row, first cell.
For xls it is HTML code added into Excel report between exported TreeGrid table and enclosing </body> tag
<Cfg> int

ExportRows

[500]
For how many rows will be displayed and updated progress bar. Displaying progress bar suppresses also message about slow script.
0 never shows progress bar. The progress bar is shown only if the count of exported rows is higher than the ExportRows value.
When shown the progress bar in IE there is shown message after finish and a user must click to download button - otherwise IE blocks the file download.
Too small value can slow down the export, reasonable value is about 100.
<cell> string

ExportValue

Cell value used for export to Excel, see also OnGetExportValue event.
new 7.0 <C> <cell> string

ExportStyle

The CSS style added to the cell when exported.
For example to align the cell vertically to top, set ExportStyle='vertical-align:top'.

It can be used also to format the number or date value in Excel, e.g. ExportStyle='mso-number-format:"$ 0.00";' or ExportStyle='mso-number-format:"d.M.yyyy HH:mm";'
The Excel CSS attribute mso-number-format settings are similar to TreeGrid number and date formats.
chg 12.1 <C> <cell> string

ExportFormat

TreeGrid date time or number format to be used instead of the cell Format for export to Excel.
See ExportFormat for number type or ExportFormat for date type.
Since 12.1 it is not used for old Xls export except for ExportType="Dates", use XlsFormat instead.
new 12.1 <C> <cell> string

XlsFormat

Excel date time or number format to be used instead of the cell Format for export to Excel.
It is exact MS Excel format string passed to CSS attribute mso-number-format.
For old Xls export only.
API event string

OnGetExportValue

(TGrid grid, TRow row, string col, string str)
Called to get value for export to Excel
str is html tag ending character ('>'), so to return just string return str+your_value and to return formatted number return your_format+str+your_value.
For example: Grids.OnGetExportValue = function(G,row,col,str){ return " style='mso-number-format:\"$ 0.00\";'"+str+Get(row,col); }
<Cfg> int

ExportRound

If set, the Float number will be rounded to this count of decimal digits.
new 7.1 <Cfg> string

CSVValueSeparator

[";"]
String or character that separates individual values in export to CSV
new 7.1 <Cfg> string

CSVRowSeparator

["&#x0a;"]
String or character that separates individual rows in export to CSV
new 7.1 <Cfg> string

CSVQuote

['"']
Character that quotes value in export to CSV, if it contains one of the ValueSeparator, RowSeparator or Quote.
The quote characters are doubled in the value.
new 7.1 <Cfg> string

CSVLevel

["#"]
String or character to show level deep, when ExportType='Outline'
new 12.1 <Cfg> bool

JSZip

[1]
If third party library JSZip will be loaded and used by TreeGrid.

JSZip is library for LZ compression. It is independent on TreeGrid. It is distributed under MIT or GPLv3 license.
It can be downloaded or its licensing read at https://stuk.github.io/jszip/

It is loaded by TreeGrid only for client export to xlsx.
To not use it at all, set <Cfg JSZip='0'/>, in this case the export will produce longer uncompressed xlsx files.

Server export

To server is sent just actual grid configuration – sorting, grouping, filters, search and column width, positions and visibility.
In "custom" parameter "ExportFormat" is sent chosen file extension "xlsx", "xls" or "csv".
In "custom" parameter "ExportName" is sent chosen file name.
In "custom" parameter "ExportType" is sent chosen ExportType flags.
For Export_Type="Settings", "Cols" or "Hidden", the rows and column are marked as visible if they were checked in export menu.

It is possible to upload also other data from client like changes, set Export_Type="Settings,Changes".
The configuration is sent as standard TreeGrid XML in Data attribute.
Server must generate the report from data on server by itself and return report to client.
Use this way for larger grid and/or for grids with server paging or server child paging.
Use it also if you want to generate different then standard report or you want to generate report for another program then MS Excel.

XML structure of request for server export

Used as request sent to data source Export to get the exported grid when set server side export (Export_Type="Settings").
It contains session identification and grid configuration to sort, group, filter and search exported data on server.
It contains also columns settings - width, position and visibility.

<Grid>
<IO ... attributes with request settings ... /> (Session attribute)
<Cfg ... attributes with grid settings read from cookies ... />
(HiddenRows, Sort, Group, ReSort, ReCalc, TimeZone attributes)
(SearchAction, SearchExpression, SearchType, SearchMethod, SearchDefs, SearchCols attributes)
(Focused, FocusedCol, FocusedPos attributes)
(PrintPageBreaks, PrintRows, PrintExpanded, PrintFiltered)
<Filter> (list of filters)
<I ... row and cell attributes ... /> (id attribute, cell values and cell Filter attributes)
... More tags <I> if more filters are in grid ...
</Filter>

<LeftCols>
<C Name='column name' Width='...' Visible='0/1' />
... more tags <C> for other columns ...
</LeftCols>
<Cols>
<C Name='column name' Width='...' Visible='0/1' />
... more tags <C> for other columns ...
</Cols>
<RightCols>
<C Name='column name' Width='...' Visible='0/1' />
... more tags <C> for other columns ...
</RightCols>

</Grid>