Я скомпилировал своего рода плагин для гридов в ExtJS 4. Это поможет вам сделать версию для печати и экспортировать в Excel. Он экспортирует именно то, что вы видите, и работает с визуализаторами столбцов. Включить этот скрипт:
/**
* Export grid data. Based on:
* http://www.sencha.com/forum/showthread.php?125611-data-download-function-from-Grid-and-Chart
* http://www123.ddo.jp/grid/array-grid.js
* http://edspencer.net/2009/07/extuxprinter-printing-for-any-ext.html
* @param {Object} opt (optional)
* format: 'html',
* headers: true,
* stylesheetPath: 'css/print.css'
*/
Ext.grid.GridPanel.prototype.exportData = function(opt){
opt=opt||{};
//Get the array of columns from a grid
var me=this, columns=[], data=[];
Ext.each(me.columns, function(col) {
if (col.hidden != true && col.dataIndex) columns.push(col);
});
//Sometimes there's no colum header text (when using icons)
Ext.each(columns, function(column) {
if (!column.text || column.text == ' ') {
column.text=column.dataIndex;
}
});
//Build a useable array of store data for the XTemplate
me.store.data.each(function(item) {
var convertedData = {};
//apply renderers from column model
Ext.iterate(item.data, function(key, value) {
Ext.each(columns, function(column) {
if (column.dataIndex == key) {
if (column.renderer) {
if (column.xtype==='templatecolumn') {
convertedData[key] = column.renderer(value, {}, item);
} else {
convertedData[key] = column.renderer(value, undefined, undefined, undefined, columns.indexOf(column), undefined, me.view);
}
} else {
convertedData[key] = value;
}
if (typeof convertedData[key]==='string') {
convertedData[key]=Ext.util.Format.htmlToText(convertedData[key]);
}
return false;
}
});
});
data.push(convertedData);
});
//generate finale template to be applied with the data
var headings=[], body=[], str;
if (opt.format==="html") {
headings=opt.headers?new Ext.XTemplate(
'<tr>',
'<tpl for=".">',
'<th>{text}</th>',
'</tpl>',
'</tr>'
).apply(columns):'';
body=new Ext.XTemplate(
'<tr>',
'<tpl for=".">',
'<td>\{{dataIndex}\}</td>',
'</tpl>',
'</tr>'
).apply(columns);
var str=[
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'<html>',
'<head>',
'<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
opt.stylesheetPath?'<link href="' + opt.stylesheetPath + '" rel="stylesheet" type="text/css" media="screen,print" />':'',
me.title?'<title>' + me.title + '</title>':'',
'</head>',
'<body>',
'<table>',
Ext.String.format('{0}\n<tpl for=".">{1}\n</tpl>', headings, body),
'</table>',
'</body>',
'</html>'
].join('\n');
} else {
Ext.each(columns, function(v) {
headings.push(Ext.util.Format.htmlToText(v.text));
body.push('{'+v.dataIndex+'}');
});
headings=opt.headers?headings.join('\t'):'';
body =body.join('\t');
var str=Ext.String.format('{0}\n<tpl for=".">{1}\n</tpl>', headings, body);
}
//console.log('toText', columns, data, headings, body, str);
return new Ext.XTemplate(str).apply(data);
};
Теперь напечатайте сетку примерно так:
var html=grid.exportData({
format: 'html',
headers: true,
stylesheetPath: 'resources/css/print.css'
});
var name = grid.getXType ? Ext.String.format("print_{0}_{1}", grid.getXType(), grid.id) : "print";
name=name.replace(/\W*/g, ''); //IE disallows spaces and other special characters in window name (the second argument). You need to remove them before passing as argument.
var win = window.open(undefined, name);
win.document.write(html);
win.document.close();
win.print();
Для экспорта в Excel необходимо экспортировать сетку в строку с разделителями табуляции. Эта строка, которую вы публикуете на сервере (download.php)
var html=grid.exportData({
format: 'txt',
headers: true,
stylesheetPath: 'resources/css/print.css'
});
var form = Ext.DomHelper.append(document.body, {
tag: 'form',
style: 'display:none',
action: 'download.asp',
method: 'post',
cn:[{
tag:'textarea',
name:'body',
html:html
},{
tag:'input',
name:'filename',
value: grid.title||'download'
},{
tag:'input',
name:'extension',
value:'xls'
}]
});
form.submit();
document.body.removeChild(form);
Тогда download.php должен отобразить опубликованное тело. Использование:
Content-Disposition=attachment;filename=file.xls
Content-Type=application/vnd.ms-excel
Теперь ваш браузер должен показать подсказку, в которой вас просят сохранить файл xls.