Excel工具类ExcelUtil

导出为EXCEL文件并下载

使用ExcelUtil.writeToExcel(ExcelUtil.listToWorkbook(rows, ExcelType.xls), out);方法

 

生成一个export-wsdlpath-20141023135606.xls 文件并自动下载



 

直接从数据库中查数据后填充即可。

 

/**
 * 导出选定的服务的wsdl path
 * 
 * @param info [id]
 */
@RequestMapping(value = "esbService/exportWsdlPath.do", method = RequestMethod.GET)
@ResponseBody
public void exportWsdlPath(@RequestParam String info, HttpServletResponse response){
	//logger.debug("exportWsdlPath begin...");
	
	//logger.debug("parm : " + info);
	
	//info = srvId1:srvName1,srvId2:srvName2,...         
	if(StringUtils.isNotEmpty(info)){
		// 要下载路径的服务id
		List<Long> srvId = new ArrayList<Long>();
		
		for(String si : info.split(",")){
			try {
				srvId.add(Long.parseLong(si));
			} catch (Exception e) {
				logger.error("exportWsdlPath parse parm error... " + si);
				continue;
			}
		}
		
		//logger.debug("parse parm pass...");
		
		// 拼装表格
		List<Object> rows = new ArrayList<Object>();
		
		List<String> header = new ArrayList<String>(6);
		// 服务标识
		header.add("\u670d\u52a1\u6807\u8bc6");
		// 服务英文名
		header.add("\u670d\u52a1\u82f1\u6587\u540d");
		// 服务中文名
		header.add("\u670d\u52a1\u4e2d\u6587\u540d");
		// 服务类型
		header.add("\u670d\u52a1\u7c7b\u578b");
		// 提供方系统
		header.add("\u63d0\u4f9b\u65b9\u7cfb\u7edf");
		// WSDL地址
		header.add("WSDL\u5730\u5740");
		
		rows.add(header);
		
		// 获取服务清单
		List<EsbServiceV> esv = esbServiceVDS.getServiceList(srvId);
		
		logger.debug("service list : " + esv);
		
		for(EsbServiceV s : esv){
			if(s.getWsdlUrl() == null) continue;
			List<String> row = new ArrayList<String>(6);
			row.add(s.getServiceNumber());
			row.add(s.getServiceNameEn());
			row.add(s.getServiceNameCN());
			row.add(s.getServiceTypeName());
			row.add(s.getProviderAppName());
			String adr = SysConfigCache.getConfigByName(Constants.SERVER_ADDRESS);
			if(adr.endsWith("/")){
				adr = adr.substring(0, adr.length() - 1);
			}
			row.add(adr + s.getWsdlUrl());
			rows.add(row);
		}
		
		// httpheader设置
		response.setContentType("application/x-msdownload;");  
		response.setHeader("Content-disposition", "attachment; filename = export-wsdlpath-" + String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", System.currentTimeMillis()) + ".xls");
		
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			ExcelUtil.writeToExcel(ExcelUtil.listToWorkbook(rows, ExcelType.xls), out);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(out != null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	//logger.debug("exportWsdlPath end...");
}

 

 

MAVEN POM:

 

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-scratchpad</artifactId>
	<version>3.9</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.9</version>
	<exclusions>
		<exclusion>
		<artifactId>xml-apis</artifactId>
		<groupId>xml-apis</groupId>
	</exclusion>
</exclusions>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.9</version>
</dependency>

 

 

代码:

List<Object> readToList(String fileName, int sheetIndex, int skipRows)
    //读取Excel文件数据,转换为一个List

Workbook listToWorkbook(List<?> rows, ExcelType type)
    //将List数据转换为Wordbook格式

void writeToExcel(Workbook wb, OutputStream out)
    //生成Excel文件,即将Wb转换为文件

 

转换Excel文件为List
Excel工具类ExcelUtil_第1张图片
  

List<Object> rows = null;
			try {
				rows = ExcelUtil.readToList(newName, 1, 1);
			} catch (Exception e) {
				result.put("code", 2);
				result.put("msg", e.getMessage());
				// return result;
			}

			if (result.isEmpty()) {
				// List行转ProxyService对象
				List<ProxyService> list = new ArrayList<ProxyService>(rows.size());
				Map<String, Object> ut = new HashMap<String, Object>();
				String key = "";
				try {
					for (Object obj : rows) {
						@SuppressWarnings("unchecked")
						List<String> row = (List<String>) obj;

						if (StringUtils.isNotEmpty(row.get(2)) && StringUtils.isNotEmpty(row.get(5)) && StringUtils.isNotEmpty(row.get(7))) {
							// 验证输入
							if (row.get(2).replaceAll("[a-zA-Z0-9_]", "").length() != 0)
								throw new Exception("【所属系统或模块】只能由字母、数字和下划线构成:" + row.get(2));
							if (row.get(5).replaceAll("[a-zA-Z0-9_]", "").length() != 0)
								throw new Exception("【服务名】只能由字母、数字和下划线构成:" + row.get(5));
							// 验证唯一键约束
							key = row.get(2) + "-" + row.get(5);
							if (null != ut.get(key))
								throw new Exception("【所属系统或模块】组合【服务名称】不能重复");
							ut.put(key, row);
							ProxyService service = proxyServiceService.getByName(row.get(2), row.get(5));
							if (null == service) {
								service = new ProxyService();
								service.setState(0);
							} else {
								service.setState(1);
							}
							service.setModel(row.get(2));
							service.setName(row.get(5));
							service.setWsdl(row.get(7));
							service.setDescribe(StringUtils.isNotEmpty(row.get(8)) ? row.get(8) : row.get(5));

							list.add(service);
						}
					}
					// 服务列表写入Session
					session.setAttribute(SessionKey.EXCEL_PROXYSERVICE_LIST, rows);
					session.setAttribute(SessionKey.MULTIPLE_PROXYSERVICE_LIST, list);

					// 返回结果
					result.put("code", 0);
					result.put("result", list);
				} catch (Exception e) {
					result.put("code", 3);
					result.put("msg", e.getMessage());
				}
			}

 

工具类:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {
	/**
	 * Excel文件到List
	 * @param fileName
	 * @param sheetIndex	// 工作表索引
	 * @param skipRows	// 跳过的表头
	 * @return
	 * @throws Exception 
	 */
	public static List<Object> readToList(String fileName, int sheetIndex, int skipRows) throws Exception{
		List<Object> ls = new ArrayList<Object>();
		Workbook wb = loadWorkbook(fileName);
		if (null != wb) {
			Sheet sh = wb.getSheetAt(sheetIndex);
			int rows = sh.getPhysicalNumberOfRows();
			for (int i = skipRows; i < rows; i++) {
				Row row = sh.getRow(i);
				if(null==row){
					break;
				}
				int cells = row.getPhysicalNumberOfCells();
				if(cells==0){
					continue;
				}
				List<String> r = new ArrayList<String>(cells);
				for (int c = 0; c < cells; c++) {
					if(c == 0 || c== 4){
						try{
							r.add(String.format("%.0f", row.getCell(c).getNumericCellValue()));
						}catch(Exception e){
							throw new Exception("出现该错误请依次检查:<br>1、【序号】或【端口号】请使用数字<br>2、检查《Webservice信息》是否是第二个sheet页");
						}
					}else{
						r.add(row.getCell(c).getStringCellValue());
					}
				}
				ls.add(r);
			}
		}
		
		return ls;
	}
	
	/**
	 * 读取Excel文件,支持2000与2007格式
	 * @param fileName
	 * @return
	 * @throws Exception 
	 */
	public static Workbook loadWorkbook(String fileName) throws Exception {
		if (null == fileName)
			return null;

		Workbook wb = null;
		if (fileName.toLowerCase().endsWith(".xls")) {
			try {
				InputStream in = new FileInputStream(fileName);
				POIFSFileSystem fs = new POIFSFileSystem(in);
				wb = new HSSFWorkbook(fs);
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (fileName.toLowerCase().endsWith(".xlsx")) {
			try {
				InputStream in = new FileInputStream(fileName);
				wb = new XSSFWorkbook(in);
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			throw new Exception("不是一个有效的Excel文件");
		}
		return wb;
	}
	
	public static void writeToExcel(Workbook wb, OutputStream out){
		try {
			wb.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static enum ExcelType{
		xls, xlsx;
	}
	public static Workbook listToWorkbook(List<?> rows, ExcelType type){
		Workbook wb = null;
		if(ExcelType.xls.equals(type)){
			wb = new HSSFWorkbook();
		}else if(ExcelType.xlsx.equals(type)){
			wb = new XSSFWorkbook();
		}else{
			return null;
		}
		
		Sheet sh = wb.createSheet();
		if(null!=rows){
			for(int i=0; i<rows.size(); i++){
				Object obj = rows.get(i);
				Row row = sh.createRow(i);
				
				if (obj instanceof Collection) {
					Collection<?> r = (Collection<?>) obj;
					Iterator<?> it = r.iterator();
					int j = 0;
					while(it.hasNext()){
						Cell cell = row.createCell(j++);
						cell.setCellValue(String.valueOf(it.next()));
					}
				}else if(obj instanceof Object[]){
					Object[] r = (Object[]) obj;
					for(int j=0; j<r.length; j++){
						Cell cell = row.createCell(j);
						cell.setCellValue(String.valueOf(r[j]));
					}
				}else{
					Cell cell = row.createCell(0);
					cell.setCellValue(String.valueOf(obj));
				}
			}
		}
		
		return wb;
	}
	
	public static void main(String[] args) {
		List<Object> rows = new ArrayList<Object>();
		
		List<Object> row = new ArrayList<Object>();
		row.add("字符串");
		row.add(11);
		row.add(new Date());
		row.add(1.0);
		rows.add(((Object)row));
		
		rows.add("中文");
		rows.add(new Date());
		
		listToWorkbook(rows, ExcelType.xls);
		listToWorkbook(rows, ExcelType.xlsx);
	}
}

 

。。

 

你可能感兴趣的:(Excel)