一、使用fileReference.download 下载Excel文件:
(1)<s:Button label="匯出2" id="export2" click="download()"/>
(2)private function download():void
{
var request:URLRequest = new URLRequest(
"http://localhost:8080/test/exportExcel?service=userService&method=exportUsers&args=-%2C2%2C-%2C-"); //调用servlet
var fileReference:FileReference = new FileReference();
fileReference.download(request, "excel.xls");
}
(3)
public class ExportExcelServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
String serviceName = request.getParameter("service");
String methodName = request.getParameter("method");
String arg = request.getParameter("args");
String[] args = new String[0];
if(null != arg && arg.length() > 0)
args = arg.split(",");
Object bean = ApplicationContextUtil.getBean(serviceName);
ExportData data = null;
try {
data = (ExportData)invokeMethod(bean, methodName, Arrays.asList(args));
//调用spring创建的bean
} catch (Exception e) {
e.printStackTrace();
}
// 设置返回数据类型
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
// 设置返回的文件名
response.setHeader("Content-Disposition", "attachment;Filename="
+ "data.xls");
try {
OutputStream os = response.getOutputStream();
WritableWorkbook wb = Workbook.createWorkbook(os);
wb = ExcelUtil.exportExcel(wb, data.getDataList(), data.getFields(), data.getFieldNames());
wb.write();
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private Object invokeMethod(Object owner,String methodName,List args) throws Exception{
Class ownerClass = owner.getClass();
Class[] argsClass = new Class[args.size()];
for(int i = 0; i < args.size(); i++){
argsClass[i] = args.get(i).getClass();
}
Method method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(owner,args.toArray());
}
(4)web.xml:
<!-- 数据导出 -->
<servlet>
<servlet-name>ExportExcelServlet</servlet-name>
<servlet-class>servlet.ExportExcelServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExportExcelServlet</servlet-name>
<url-pattern>/exportExcel</url-pattern>
</servlet-mapping>