extjs4.2导出excel表格
来源:互联网 发布:炒股神经病 知乎 编辑:程序博客网 时间:2024/06/05 17:38
思路:
**1、要有个java类,类里要有生成excle方法,下载文件,生成临时文件方法,获取文件方法。在ajax请求成功时,调用获取getExelcFile方法
2.要有个js导出数据的方法**
开启民工视角:
ExportExcelAction .java
package com.geoway.platform.action;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.StringReader;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.ezmorph.bean.MorphDynaBean;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.apache.batik.transcoder.TranscoderInput;import org.apache.batik.transcoder.TranscoderOutput;import org.apache.batik.transcoder.image.JPEGTranscoder;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import com.geoway.common.util.StringUtility;import com.geoway.common.util.ZipCompressorByAnt;import com.geoway.core.action.BaseAction;@Controller("exportExcelAction")@Scope("prototype")public class ExportExcelAction extends BaseAction { private final Logger logger = Logger.getLogger(ExportExcelAction.class); public void export() throws Exception{ HttpServletRequest request = ServletActionContext.getRequest(); String exportData = request.getParameter("exportData"); String uuid = StringUtility.getUUID(); JSONObject jSONObject = JSONObject.fromObject(exportData); JSONObject excelObject = jSONObject.getJSONObject("excelData"); String fileName = (String) excelObject.get("name"); if(fileName ==null || fileName ==""){ throw new Exception("统计结果为空,不可导出!"); } //临时文件路径初始化 String tmpDirName = this.getTmpDirName(uuid); //生成EXCEL this.createExcelFile(excelObject, tmpDirName); String filePath = this.createExcelFile(excelObject, tmpDirName).toString();// download(this.createExcelFile(excelObject, tmpDirName)); JSONArray jSONArray = jSONObject.getJSONArray("chartsData"); List<MorphDynaBean> i = (List<MorphDynaBean>) JSONArray.toCollection(jSONArray); //生成图表 for(MorphDynaBean bean : i){ this.createChart(bean, tmpDirName); } //需求改变,要下载xls格式,压缩功能先不用// String zip = tmpDirName.substring(0,tmpDirName.length()-1) + ".zip";// ZipCompressorByAnt zca = new ZipCompressorByAnt(zip); //apache ant方式压缩// zca.compress(tmpDirName); this.sendJSONWeb("{success:true,uuid:'" + uuid + "'}"); } public void getExcelFile() throws UnsupportedEncodingException{ HttpServletRequest request = ServletActionContext.getRequest(); String exportData = request.getParameter("exportData"); String uuid = request.getParameter("uuid"); //获得并拼接压缩包的名字 String tempName = request.getParameter("name").toString(); String zipName=java.net.URLDecoder.decode(tempName,"UTF-8"); zipName = zipName.replaceAll(" ", "") + this.getCurrentDateTime(); //临时文件路径初始化 String tmpDirName = this.getTmpDirName(uuid); String downPath = tmpDirName.substring(0,tmpDirName.length()-1) + "\\统计数据.xls"; //D:\temp\73292191\统计数据.xls //D:/temp\73292191\统计数据.xls File file = new File(downPath); ServletOutputStream outputStream = null; InputStream inputStream = null; try { inputStream = new FileInputStream(file); HttpServletResponse response = ServletActionContext.getResponse(); response.reset(); response.setContentType("zip/*"); String serverName = request.getServerName(); String Location = "http://" + serverName + "//"; response.setHeader("Content-Location", Location); response.setHeader("Content-Disposition","attachment;filename="+new String((zipName.trim()).getBytes("gb2312"), "ISO8859-1")+".xls"); response.flushBuffer(); outputStream = response.getOutputStream(); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (null != outputStream) { outputStream.close(); } if (null != inputStream) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); } } } /** * 获得临时路径 * @param uuid * @return */ private String getTmpDirName(String uuid){ String tempSavePath = "D:/temp";// try {// tempSavePath = PropertiesUtility.getInstance().getProperties("appconfigZlgl", "app.temp_export_path");// } catch (CommonException e) {// logger.error(e.getMessage());// throw new ActionException("没有配置导出临时空间");// }// if(tempSavePath == null){// logger.error("没有配置导出临时空间");// throw new ActionException("没有配置导出临时空间");// } //创建临时文件夹 String dir = tempSavePath+File.separator+uuid+File.separator; File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } private File createChart(MorphDynaBean bean,String tmpDirName) throws Exception{ String svgString = ""; String fileName = ""; try{ svgString = (String) bean.get("data"); fileName = (String) bean.get("name"); }catch(Exception e){ e.getStackTrace(); throw new Exception("统计结果为空,不可导出!"); } fileName = tmpDirName + fileName + ".jpg"; File file = new File(fileName); OutputStream out = new FileOutputStream(file); JPEGTranscoder t = new JPEGTranscoder(); t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(.8)); TranscoderInput input = new TranscoderInput(new StringReader(svgString)); try { TranscoderOutput output = new TranscoderOutput(out); t.transcode(input, output); out.flush(); out.close(); return file; }catch (Exception e){ out.flush(); out.close(); e.printStackTrace(); return file; } } **ExportExcel.js** /** * 导出EXCEL * @param excelObject * @param tmpDirName * @return * @throws IOException */ private File createExcelFile(JSONObject excelObject,String tmpDirName) throws IOException{ String fileName = (String) excelObject.get("name"); String data = (String)excelObject.get("data"); System.out.println(data); fileName = tmpDirName + fileName + ".xls"; File file = new File(fileName); BufferedOutputStream buff = new BufferedOutputStream(new FileOutputStream(file)); ; Writer out = new OutputStreamWriter(buff, "UTF-8"); out.write(data); out.close(); buff.close(); buff.close(); return file; } public String getCurrentDateTime() { SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String s = df.format(new Date()); return s; }}
Ext.define('ExportExcel', { /** * 导出 * grid实例 * charts实例数组 */ //TODO 放到别的包下 exprotData:function(grid,charts){ var statisticsExport = getRootPath()+'/platform/exportExportExcelAction.action'; var statisticsGetFile = getRootPath()+'/platform/getExcelFileExportExcelAction.action';// var doStatistics = _ctxPath+'/exceptionCheck/doStatisticsStatisticsAction.action'; var exportData = {}; exportData['excelData'] = grid.getExportData(); var chartsData = []; for(var i = 0;i < charts.length ; i ++){ chartsData.push(charts[i].items.items[0].getExportData()); } exportData.chartsData = chartsData; var postObject = {}; var name = exportData.excelData.name; name = encodeURI(encodeURI(name)); postObject.exportData = Ext.encode(exportData); Ext.Ajax.request({ url: statisticsExport, method : 'post', scope : this, timeout : 60000, params: postObject, success: function(response){ var res = Ext.decode(response.responseText); if(res.success == true){ var url = statisticsGetFile + "?uuid="+res.uuid+"&name="+name; window.open(url); } } }); }});
前台调用ExportExcel方法:
var exportExcelButton = Ext.create('Ext.button.Button',{ hidden : true, cls:'.mybutton', text: '<span style="font-size:13px; font-weight:normal">保存</span>', margin: '6 70 0 10',//(top, right, bottom, left) scope:this, handler: function() { var exportExcel = Ext.create('ExportExcel',{}); exportExcel.exprotData(this.grid,''); } });
0 0
- extjs4.2导出excel表格
- Extjs4---后台导出excel poi
- ExtJS4+SSH 实现Excel导出
- Extjs4---grid导出excel文件,前台导出
- ExtJS4.2 树形表格
- tp3.2中excel表格导出数据
- javascript表格导出Excel
- (表格)导出excel
- 【Java】导出excel表格
- JAVA 导出 excel 表格
- C#导出EXCEL表格
- Java导出excel表格
- 【Java】导出excel表格
- java 导出excel表格
- 导出Excel表格
- C#导出excel表格
- Java导出Excel表格
- Java导出excel表格
- linux内核进程退出分析
- ARC 下的内存泄露
- 修改配置参数后无法启程MySQL数据库
- 博文要有的元素
- iOS 开发之 pdf 文档的加载与浏览的 4 种方式
- extjs4.2导出excel表格
- Java Expression Language (JEXL)
- redis 数据类型详解 以及 redis适用场景场合
- Android线程及进程笔记
- chrome打不开plugins
- 各大互联网公司前端笔试面试题–HTML,CSS篇
- 用PHP实现一个关于德州扑克算法的程序(四):代码
- Android提示BOM错误排查
- Ubuntu shadowsocks https_proxy