天天看点

JAVA整合Flex导出数据库中的数据 (续)

根据上一章的介绍,如果有新的需求来了怎么办,比如说要从服务器端的文件中写,然后输出至客户端呢,没关系。其实也思路明白啦,也很简单,如下所示:

1. 在服务器中组装数据

1.1 组装Excel的包装类,如下所示:

package cn.ac.iscas.gz.sems.web.common.dataimport;

import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 * Excel操作类(职责:组装数据,设定样式等)
 * 2013-08-22
 */
public class ExcelFileAssembly {
	
  /** 使用单例模式 **/
  public static ExcelFileAssembly excelFileAssembly = new ExcelFileAssembly();
  
  public static ExcelFileAssembly getInstance(){
	  if(excelFileAssembly == null){
		  excelFileAssembly = new ExcelFileAssembly();
	  }
	  return excelFileAssembly;
  }
  
/**
 * 组装数据至excel文件中
 * @param path
 * @param filename
 * @param response
 * @param sample_data
 * @throws Exception
 */
  public  void assembleData(String path, String filename, HttpServletResponse response,
		  					Object[][] sample_data) throws Exception {
	  
	  InputStream inputStream = new FileInputStream(path + filename);
	  
	  //从流中得到Workbook
	  Workbook wb = WorkbookFactory.create(inputStream);
	  
	  //得到第一个sheet
	  Sheet sheet = wb.getSheetAt(0);

      //设置数据
      for (int i = 0; i < sample_data.length; i++) {
          Row row = sheet.getRow(1 + i);
          for (int j = 0; j < sample_data[i].length; j++) {
              if(sample_data[i][j] == null) continue;

              if(sample_data[i][j] instanceof String) {
                  row.getCell(j).setCellValue((String)sample_data[i][j]);
              } else if(sample_data[i][j] instanceof Double){
                  row.getCell(j).setCellValue((Double)sample_data[i][j]);
              }else if(sample_data[i][j] instanceof Long){
                  row.getCell(j).setCellValue((Long)sample_data[i][j]);
              }else if(sample_data[i][j] instanceof Integer){
                  row.getCell(j).setCellValue((Integer)sample_data[i][j]);
              }
          }
      }

      // Write the output to a response object
      wb.write(response.getOutputStream());
  }

}
           

1.2 输出至controller层,其只要是以流的形式,发送至客户端,它的部分代码,如下所示:

@RequestMapping(params ="action=exportExcel", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.HEAD})
    public void excel(HttpServletRequest request, HttpServletResponse response)  throws Exception{
		 String filename = "节点控制器";	 
		 String isTemplate = request.getParameter("isTemplate");
		 int isTemplateNum = Integer.parseInt(isTemplate);
		 
		 String concentUID = request.getParameter("concentUID");
		 String groupMaintainId = request.getParameter("groupMaintainId");

		 Object[][] nodeDevice_datas = {{}};
		
		 
		try{
			List<NodeDevice> nodeDeviceList;
			 if(isTemplateNum == SemsConstants.IS_TEMPLEATE){
				 filename = "节点控制器数据导入模板.xls";
			 }
			 if(isTemplateNum == SemsConstants.IS_NOT_TEMPLEATE){
				if(("0").equals(groupMaintainId)){
					nodeDeviceList = nodeDeviceService.findAllNodeDeviceByConcentUid(concentUID);
					filename += "("  + concentUID + ")" +".xls";
				}else{
					Long groupId = Long.parseLong(groupMaintainId);
				   nodeDeviceList = nodeDeviceService.findAllNodeDeviceByGroupMaintainId(groupId);
				   GroupMaintainEntity entity = groupMaintainService.get(GroupMaintainEntity.class, groupId);
				   filename += "("  + entity.getName() + ")" + ".xls";
				}
			
				 if(nodeDeviceList != null){
					 nodeDevice_datas = new Object[nodeDeviceList.size()][];
					//包装数据
					for (int i = 0 ; i < nodeDeviceList.size(); i++){
						NodeDevice nodeDevice = nodeDeviceList.get(i);
						Object [] itemObject = {String.valueOf(i+1), nodeDevice.getUid(), nodeDevice.getName(),
								  Integer.parseInt(nodeDevice.getType()),  Double.parseDouble(nodeDevice.getLongitude()),
								  Double.parseDouble(nodeDevice.getLatitude()),
								  nodeDevice.getLocationDesc(), nodeDevice.getRemark()
						}; 
						nodeDevice_datas[i] = itemObject;
					}
			     }
			}
			 
			 //设置输出的文件名称,支持中文
			 HttpWebUtil.responseExportExcelConfig(response, filename);
			 
			 //读取其路径
			 String nodeDevicePath = servletContext.getRealPath("/") + "flex4\\tpl\\" ;
			 
			 
			  //导出数据至Excel表格中
			  ExcelFileAssembly.getInstance().assembleData(
					   nodeDevicePath,"节点控制器数据导入模板.xls",
					   response, 
					   nodeDevice_datas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
           

1.3.客户端的代码无变化,如果要输出至本页面,可以将其改成

/**
			 * 模板下载
			 **/ 
			protected function templeateButton_clickHandler(event:MouseEvent):void
			{
				var url:String = getFileAddress(areaSelecter.selectedItem.id, concSelecter.selectedItem.label, groupSelecter.selectedItem.id, 1);
				var u:URLRequest = new URLRequest(url);
				
				u.method = URLRequestMethod.POST;
				navigateToURL(u,"_self");
			}
           

(完,待续...............................)

继续阅读