java实现excel的导入导出(poi)

首先我们要知道MS excel文件由什么组成,比如说sheet(一个工作表格),表格的行,单元格,单元格格式,单元格内容格式…这些都对应着poi里面的一个类。

一个excel表格:HSSFWorkbook wb = new HSSFWorkbook();

或者  XSSFWorkbook wb = new XSSFWorkbook();

一个工作表格:HSSFSheet sheet = wb.createSheet("表格");

一行:HSSFRow row = sheet.createRow(0);

一个单元格(cell)HSSFCell cell = row.createCell((short)0)

单元格格式(cellstyle):HSSFCellStyle style = wb.createCellStyle()

单元格内容格式:HSSFDataFormat format= wb.createDataFormat();

读写xls和xlsx不同格式的excel文档时,HSSFWorkbook针对.xls,XSSFWorkbook针对.xlsx的格式。

PS:xlsx是Microsoft Office EXCEL 2007文档的扩展名。xlsx是Office2007使用的,是用新的基于XML的压缩文件格式取代了其目前专有的默认文件格式,在传统的文件名扩展名后面添加了字母x(即:docx取代doc、.xlsx取代xls等等),使其占用空间更小。

一、导入Excel表格

导入.xls格式的excel表格,读取、筛选其中的内容。将正确的内容存入系统中,提示用户错误导入的数目,并提供用户下载导入失败的条目。

@RequiresPermissions("repair:repairItem:edit")
	@RequestMapping(value = "importExcel")
	public String repairItemInfoInport(MultipartFile repairItemExcel, HttpServletRequest request,RedirectAttributes redirectAttributes,Model model) throws InvalidFormatException, IOException {
		CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		User user =UserUtils.getUser();
		
		Community community = user.getCommunity();    	
		String communityId = community.getId();
		Map<String, Object> result = new HashMap<String, Object>();
		List<List<Object>> errorExcel=new ArrayList<>();
		String Filename = repairItemExcel.getOriginalFilename();
		// 判断条件:1.导入Excel文件后缀必须为.xls    
		if (Filename.contains(".xls")&& resolver.isMultipart(request)  && (StringUtils.isNotBlank(communityId)&& null != repairItemExcel)) {
			String[] header = {};
			List<List<Object>> data = new ArrayList<>();
			try {
				InputStream is = repairItemExcel.getInputStream();
				header = excelReader.readExcelTitle(is);
				data = excelReader.readExcelContent(is);
				is.close();
			} catch (IOException e) {
				logger.debug("Import fail");
				addMessage(model, "导入失败");
			}
			if (data.size() != 0 && header != null) {
				/*
                把表格中的数据写到数据表中
				 */
				result = repairItemService.txaddExcelRepairItem(data,communityId);
				if(result==null||"".equals(result)){
					logger.debug("Import fail");
					addMessage(model, "导入失败,请检查导入表格的格式是否符合模板中的要求");
					return importItem(model);
				}
				// 创建ImportExcel操作对象ei
				ImportExcel ei = null;
				 try {
					 ei=new ImportExcel(repairItemExcel, 0, 0);
				 }catch (Exception e) {
			            e.printStackTrace();
			            addMessage(model, "操作失败,请重试!");
			        }
				// 获取导入错误数据
		        for (Map<String, Object> m : (List<Map<String, Object>>) result.get("errorRowList")) {
		            Integer rowNumber = (Integer) m.get("errorRow");
		            Row row = ei.getRow(rowNumber);
		            List<Object> list = new ArrayList<>();
		            boolean passFlag = false;
		            for (int j = 0; j <= ei.getLastCellNum(); j++) {
		                Object val = ei.getCellValue(row, j);
		                String s = null;
		                if (val instanceof Double) {
		                    s = new DecimalFormat("0").format(val);
		                } else {
		                    s = val.toString();
		                }
		                if (s.indexOf("测试") != -1) {
		                    passFlag = true;
		                    break;
		                }
		                if (j <= 4 || StringUtils.isNotBlank(s)) {
		                    list.add(s);
		                }
		            }
		            if (passFlag) {
		                continue;
		            }
		            list.add(m.get("message"));
		            errorExcel.add(list);
		        }
		        // 写出导入错误的数据excel
		        this.errorData=errorExcel;
		        
				 // 成功条数
		        Integer successNumber = (Integer) result.get("successNumber");
		        // 失败条数
		        Integer errorNumber = (Integer) result.get("errorNumber");
		        if (errorNumber == null || errorNumber == 0) {
		            addMessage(redirectAttributes, "成功导入所有");
		        } else {
		            addMessage(redirectAttributes, "成功导入" + successNumber + "条," + errorNumber + "条导入失败!");
		        }
			}
		}else{
			addMessage(model, "导入失败,请选择.xls文件");
			return importItem(model);
		} 
		return "redirect:"+Global.getAdminPath()+"/repair/repairItem/?repage";
	}

    /**
     * 导出错误的excel
     *
     * @param response
     */
    @RequestMapping("exportError")
    public void exportError(HttpServletResponse response) {
        // 写出错误记录excel
        if (errorData != null && !errorData.isEmpty()) {
            String[] headers = {"类型",  "名称", "单价(元)", "单位", "备注","错误信息"};
            try {
                WriteExcelUtil.writeExcel(response, "错误记录", headers, errorData);
                errorData.removeAll(errorData);
                errorData.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

操作Excel表格的功能类  ExcelReader.java 

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 操作Excel表格的功能类
 */
public class ExcelReader {
    private POIFSFileSystem fs;
    private HSSFWorkbook wb;
    private HSSFSheet sheet;
    private HSSFRow row;

    /**
     * 读取Excel表格表头的内容
     * @param
     * @return String 表头内容的数组
     */
    public String[] readExcelTitle(InputStream is) {
        try {
            fs = new POIFSFileSystem(is);
            //is.close();
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sheet = wb.getSheetAt(0);
        row = sheet.getRow(0);
        // 标题总列数
        int colNum = row.getPhysicalNumberOfCells();
        /*System.out.println("colNum:" + colNum);*/
        String[] title = new String[colNum];
        int i;
        for ( i = 0; i < colNum; i++) {
            //title[i] = getStringCellValue(row.getCell((short) i));
            title[i] = getCellFormatValue(row.getCell((short) i));
        }

        return title;
    }

    /**
     * 读取Excel数据内容
     * @param
     * @return Map 包含单元格数据内容的Map对象
     */
    /*public List<String[]> readExcelContent(InputStream is) {
        List<String[]> content = new ArrayList<>();
        String str = "";
        try {
            fs = new POIFSFileSystem(is);
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题


        for (int i = 1; i <= rowNum; i++) {
            String[] temp=new String[colNum];
            row = sheet.getRow(i);
            int j = 0;

            while (j < colNum) {
                // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
                // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
                // str += getStringCellValue(row.getCell((short) j)).trim() +
                // "-";
                temp[j]=getCellFormatValue(row.getCell( j)).trim();
//                temp[j]=str;
                j++;
            }
            content.add(temp);
            str = "";
        }
        return content;
    }*/
    /**
     * 读取Excel数据内容
     * @param
     * @return  List<List<Object>>包含单元格数据内容的List<List<Object>>对象
     */
        public List<List<Object>> readExcelContent(InputStream is) {
        /*try {
            //fs = new POIFSFileSystem(is);
            //is.close();
            //wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        int rowNum = sheet.getLastRowNum();

        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        List<List<Object>> data = new ArrayList<List<Object>>();
        List<Object> l;
        for (int i = 1; i <= rowNum; i++) {
            l = new ArrayList<Object>();
            row = sheet.getRow(i);
            int j = 0;
            while (j < colNum) {
                // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
//                if (getCellFormatValue(row.getCell(j)))

                l.add(getStringCellValue(row.getCell(j)).trim());
                j++;
            }
            data.add(l);
        }
        return data;
    }

    /**
     * 获取单元格数据内容为字符串类型的数据
     *
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
    private String getStringCellValue(HSSFCell cell) {
        String strCell = "";
        if (cell==null){
            return strCell;
        }
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_STRING:
                strCell = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                DecimalFormat df = new DecimalFormat("#");
                strCell = df.format(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                strCell = String.valueOf(cell.getBooleanCellValue());
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                strCell = "";
                break;
            default:
                strCell = "";
                break;
        }
        if (strCell.equals("") || strCell == null) {
            return "";
        }
        if (cell == null) {
            return "";
        }
        return strCell;
    }

    /**
     * 获取单元格数据内容为日期类型的数据
     *
     * @param cell
     *            Excel单元格
     * @return String 单元格数据内容
     */
    private String getDateCellValue(HSSFCell cell) {
        String result = "";
        try {
            int cellType = cell.getCellType();
            if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
                Date date = cell.getDateCellValue();
                result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)
                        + "-" + date.getDate();
            } else if (cellType == HSSFCell.CELL_TYPE_STRING) {
                String date = getStringCellValue(cell);
                result = date.replaceAll("[年月]", "-").replace("日", "").trim();
            } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
                result = "";
            }
        } catch (Exception e) {
            System.out.println("日期格式不正确!");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据HSSFCell类型设置数据
     * @param cell
     * @return
     */
    private String getCellFormatValue(HSSFCell cell) {
        String cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                // 如果当前Cell的Type为NUMERIC
                case HSSFCell.CELL_TYPE_NUMERIC:
                case HSSFCell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则,转化为Data格式

                        //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
                        //cellvalue = cell.getDateCellValue().toLocaleString();

                        //方法2:这样子的data格式是不带带时分秒的:2011-10-12
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        cellvalue = sdf.format(date);

                    }
                    // 如果是纯数字
                    else {
                        // 取得当前Cell的数值
                        cellvalue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                // 如果当前Cell的Type为STRIN
                case HSSFCell.CELL_TYPE_STRING:
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                // 默认的Cell值
                default:
                    cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;

    }
}

导入Excel文件(支持“XLS”和“XLSX”格式):  ImportExcel.java 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.qwkj.zxl.common.utils.Reflections;
import com.qwkj.zxl.common.utils.excel.annotation.ExcelField;
import com.qwkj.zxl.modules.sys.utils.DictUtils;

/**
 * 导入Excel文件(支持“XLS”和“XLSX”格式)
 * @author ThinkGem
 * @version 2013-03-10
 */
public class ImportExcel {
	
	private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
			
	/**
	 * 工作薄对象
	 */
	private Workbook wb;
	
	/**
	 * 工作表对象
	 */
	private Sheet sheet;
	
	/**
	 * 标题行号
	 */
	private int headerNum;
	
	/**
	 * 构造函数
	 * @param path 导入文件,读取第一个工作表
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, int headerNum) 
			throws InvalidFormatException, IOException {
		this(new File(fileName), headerNum);
	}
	
	/**
	 * 构造函数
	 * @param path 导入文件对象,读取第一个工作表
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(File file, int headerNum) 
			throws InvalidFormatException, IOException {
		this(file, headerNum, 0);
	}

	/**
	 * 构造函数
	 * @param path 导入文件
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @param sheetIndex 工作表编号
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, int headerNum, int sheetIndex) 
			throws InvalidFormatException, IOException {
		this(new File(fileName), headerNum, sheetIndex);
	}
	
	/**
	 * 构造函数
	 * @param path 导入文件对象
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @param sheetIndex 工作表编号
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(File file, int headerNum, int sheetIndex) 
			throws InvalidFormatException, IOException {
		this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
	}
	
	/**
	 * 构造函数
	 * @param file 导入文件对象
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @param sheetIndex 工作表编号
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex) 
			throws InvalidFormatException, IOException {
		this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
	}

	/**
	 * 构造函数
	 * @param path 导入文件对象
	 * @param headerNum 标题行号,数据行号=标题行号+1
	 * @param sheetIndex 工作表编号
	 * @throws InvalidFormatException 
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) 
			throws InvalidFormatException, IOException {
		if (StringUtils.isBlank(fileName)){
			throw new RuntimeException("导入文档为空!");
		}else if(fileName.toLowerCase().endsWith("xls")){    
			this.wb = new HSSFWorkbook(is);    
        }else if(fileName.toLowerCase().endsWith("xlsx")){  
        	this.wb = new XSSFWorkbook(is);
        }else{  
        	throw new RuntimeException("文档格式不正确!");
        }  
		if (this.wb.getNumberOfSheets()<sheetIndex){
			throw new RuntimeException("文档中没有工作表!");
		}
		this.sheet = this.wb.getSheetAt(sheetIndex);
		this.headerNum = headerNum;
		log.debug("Initialize success.");
	}
	
	/**
	 * 获取行对象
	 * @param rownum
	 * @return
	 */
	public Row getRow(int rownum){
		return this.sheet.getRow(rownum);
	}

	/**
	 * 获取数据行号
	 * @return
	 */
	public int getDataRowNum(){
		return headerNum+1;
	}
	
	/**
	 * 获取最后一个数据行号
	 * @return
	 */
	public int getLastDataRowNum(){
		return this.sheet.getLastRowNum()+headerNum;
	}
	
	/**
	 * 获取最后一个列号
	 * @return
	 */
	public int getLastCellNum(){
		return this.getRow(headerNum).getLastCellNum();
	}
	
	/**
	 * 获取单元格值
	 * @param row 获取的行
	 * @param column 获取单元格列号
	 * @return 单元格值
	 */
	public Object getCellValue(Row row, int column){
		Object val = "";
		try{
			Cell cell = row.getCell(column);
			if (cell != null){
				if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
					val = cell.getNumericCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
					val = cell.getStringCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
					val = cell.getCellFormula();
				}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
					val = cell.getBooleanCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
					val = cell.getErrorCellValue();
				}
			}
		}catch (Exception e) {
			return val;
		}
		return val;
	}
	
	/**
	 * 获取导入数据列表
	 * @param cls 导入对象类型
	 * @param groups 导入分组
	 */
	public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
		List<Object[]> annotationList = Lists.newArrayList();
		// Get annotation field 
		Field[] fs = cls.getDeclaredFields();
		for (Field f : fs){
			ExcelField ef = f.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type()==0 || ef.type()==2)){
				if (groups!=null && groups.length>0){
					boolean inGroup = false;
					for (int g : groups){
						if (inGroup){
							break;
						}
						for (int efg : ef.groups()){
							if (g == efg){
								inGroup = true;
								annotationList.add(new Object[]{ef, f});
								break;
							}
						}
					}
				}else{
					annotationList.add(new Object[]{ef, f});
				}
			}
		}
		// Get annotation method
		Method[] ms = cls.getDeclaredMethods();
		for (Method m : ms){
			ExcelField ef = m.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type()==0 || ef.type()==2)){
				if (groups!=null && groups.length>0){
					boolean inGroup = false;
					for (int g : groups){
						if (inGroup){
							break;
						}
						for (int efg : ef.groups()){
							if (g == efg){
								inGroup = true;
								annotationList.add(new Object[]{ef, m});
								break;
							}
						}
					}
				}else{
					annotationList.add(new Object[]{ef, m});
				}
			}
		}
		// Field sorting
		Collections.sort(annotationList, new Comparator<Object[]>() {
			public int compare(Object[] o1, Object[] o2) {
				return new Integer(((ExcelField)o1[0]).sort()).compareTo(
						new Integer(((ExcelField)o2[0]).sort()));
			};
		});
		//log.debug("Import column count:"+annotationList.size());
		// Get excel data
		List<E> dataList = Lists.newArrayList();
		for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
			E e = (E)cls.newInstance();
			int column = 0;
			Row row = this.getRow(i);
			StringBuilder sb = new StringBuilder();
			for (Object[] os : annotationList){
				Object val = this.getCellValue(row, column++);
				if (val != null){
					ExcelField ef = (ExcelField)os[0];
					// If is dict type, get dict value
					if (StringUtils.isNotBlank(ef.dictType())){
						val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
						//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
					}
					// Get param type and type cast
					Class<?> valType = Class.class;
					if (os[1] instanceof Field){
						valType = ((Field)os[1]).getType();
					}else if (os[1] instanceof Method){
						Method method = ((Method)os[1]);
						if ("get".equals(method.getName().substring(0, 3))){
							valType = method.getReturnType();
						}else if("set".equals(method.getName().substring(0, 3))){
							valType = ((Method)os[1]).getParameterTypes()[0];
						}
					}
					//log.debug("Import value type: ["+i+","+column+"] " + valType);
					try {
						if (valType == String.class){
							String s = String.valueOf(val.toString());
							if(StringUtils.endsWith(s, ".0")){
								val = StringUtils.substringBefore(s, ".0");
							}else{
								val = String.valueOf(val.toString());
							}
						}else if (valType == Integer.class){
							val = Double.valueOf(val.toString()).intValue();
						}else if (valType == Long.class){
							val = Double.valueOf(val.toString()).longValue();
						}else if (valType == Double.class){
							val = Double.valueOf(val.toString());
						}else if (valType == Float.class){
							val = Float.valueOf(val.toString());
						}else if (valType == Date.class){
							val = DateUtil.getJavaDate((Double)val);
						}else{
							if (ef.fieldType() != Class.class){
								val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
							}else{
								val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), 
										"fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
							}
						}
					} catch (Exception ex) {
						log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
						val = null;
					}
					// set entity value
					if (os[1] instanceof Field){
						Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
					}else if (os[1] instanceof Method){
						String mthodName = ((Method)os[1]).getName();
						if ("get".equals(mthodName.substring(0, 3))){
							mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
						}
						Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
					}
				}
				sb.append(val+", ");
			}
			dataList.add(e);
			log.debug("Read success: ["+i+"] "+sb.toString());
		}
		return dataList;
	}

//	/**
//	 * 导入测试
//	 */
//	public static void main(String[] args) throws Throwable {
//		
//		ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
//		
//		for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
//			Row row = ei.getRow(i);
//			for (int j = 0; j < ei.getLastCellNum(); j++) {
//				Object val = ei.getCellValue(row, j);
//				System.out.print(val+", ");
//			}
//			System.out.print("\n");
//		}
//		
//	}

}

二、导出项目中存在的Excel模板

@RequiresPermissions("repair:repairItem:edit")
@RequestMapping(value = "exportExcel")
public void repairItemExportTemplateDown(HttpServletResponse response,HttpSession session){
	try {
		//读写xls和xlsx格式时,HSSFWorkbook针对xls,XSSFWorkbook针对xlsx
		HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(session.getServletContext().getRealPath("/") + "excel\\导入模板.xls"));
		//response.setHeader("Content-disposition", "filename= repairItem.xls");
		//repairItemService.downRepairItemMould(header, response.getOutputStream());
		response.setHeader("Content-Disposition", "attachment;filename=" + new String("导入模板.xls".getBytes(), "ISO-8859-1"));
		wb.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

123404_lvwf_2250656.png

175335_u7JT_2250656.png

三、系统页面中的列表内容以excel表格的形式导出

@RequestMapping("exportPayBillRecord")
    public void exportPayBillRecord(PayBillrecord payBillrecord, HttpServletResponse response) {
        List<PayBillrecord> PayBillrecordLists = payBillrecordService.findList(payBillrecord);
        List<List<Object>> data = new ArrayList<List<Object>>();
		List<PayBillrecord> countList=payBillrecordService.findList(payBillrecord);
		//所缴金额总数
		BigDecimal countMoney =new BigDecimal("0");
		for(int i=0; i<countList.size();i++){
			countMoney=countMoney.add(countList.get(i).getPaymoney());
		}
        // 制作data
        for (PayBillrecord PayBillrecordList : PayBillrecordLists) {
            List<Object> list = new ArrayList<Object>();
            list.add(PayBillrecordList.getCostBillNo());
            list.add(PayBillrecordList.getTradeNo());
            list.add(PayBillrecordList.getPayTypeName());
            list.add(PayBillrecordList.getPaymoney());
            if(PayBillrecordList.getUser()!=null){
            list.add(PayBillrecordList.getUser().getUserRealName());
            }
            else{
            	list.add("");
            }
            list.add(PayBillrecordList.getCommunity().getName());
            data.add(list);
        }
        String[] headers = {"缴费单号", "交易单号", "缴费类型", "所缴金额", "缴费方式", "缴费人","所属小区","缴费时间"};
        try {
            WriteExcelUtil.writeExcel(response, "缴费历史信息统计", headers, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
* 写出普通的excel
*
* @param response HttpServletResponse
* @param fileName 写出文件的文件名,若没有添加文件类型后缀,则默认添加".xls"
* @param headers  标题行内容
* @param data     数据行内容(需要和标题行顺序一样,只支持各种普通类型)
*/
public static void writeExcel(HttpServletResponse response, String fileName, String[] headers, List<List<Object>> data) throws IOException {
    // 基础操作
    HSSFWorkbook workbook = baseHandle(headers, data);
    // 文件名操作
    fileNameHandle(response, fileName);
    // 写出excel
    workbook.write(response.getOutputStream());
}

导出的实际效果图如下:

124714_m49n_2250656.png

124735_qtlh_2250656.png

还封装了一下写出Excel的工具类:  WriteExcelUtil.java

package com.qwkj.zxl.common.utils.excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.CellRangeAddressList;
import org.apache.poi.hssf.util.HSSFColor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 2016/3/9
 * 写出Excel工具类
 */
public class WriteExcelUtil {
    /**
     * 写出带有选择框限制的excel
     * @param response HttpServletResponse
     * @param fileName 写出文件的文件名,若没有添加文件类型后缀,则默认添加".xls"
     * @param headers  标题行内容
     * @param data  数据行内容(需要和标题行顺序一样,只支持各种普通类型)
     * @param maps  需要做选择框限制的列的集合  说明:1.map中key为"titleContent"中需存入,需要做选择框的列顶部标题内容  2.map中key为"data"中需存入,所能选择的数据集合
     * @throws Exception
     */
    public static void writeExcelHaveSelectBox(HttpServletResponse response, String fileName, String[] headers, List<List<Object>> data, List<Map<String, Object>> maps) throws Exception {
        if(maps == null || maps.isEmpty()){
            throw new RuntimeException("参数maps为空");
        }
        // 基础操作
        HSSFWorkbook workbook = baseHandle(headers, data);
        // 文件名操作
        fileNameHandle(response, fileName);
        // 如果maps里有数据,则生成选择框限制
        writeSelectionBox(headers, maps, workbook);
        // 写出文件
        workbook.write(response.getOutputStream());
    }
    /**
     * 写出普通的excel
     *
     * @param response HttpServletResponse
     * @param fileName 写出文件的文件名,若没有添加文件类型后缀,则默认添加".xls"
     * @param headers  标题行内容
     * @param data     数据行内容(需要和标题行顺序一样,只支持各种普通类型)
     */
    public static void writeExcel(HttpServletResponse response, String fileName, String[] headers, List<List<Object>> data) throws IOException {
        // 基础操作
        HSSFWorkbook workbook = baseHandle(headers, data);
        // 文件名操作
        fileNameHandle(response, fileName);
        // 写出excel
        workbook.write(response.getOutputStream());
    }
    /**
     * 写出excel的一些基础操作
     * @param headers      标题行内容
     * @param data         数据行内容
     * @return 返回操作的HSSFWorkbook
     * @throws Exception
     */
    private static HSSFWorkbook baseHandle(String[] headers, List<List<Object>> data) throws IOException {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 写入标题行
        writeTitleRow(headers, workbook);
        // 如果data有数据,则遍历集合数据,产生数据行
        if(data != null && !data.isEmpty()){
            writeDataRow(data, workbook);
        }
        // 返回操作的HSSFWorkbook
        return workbook;
    }

    /**
     * 文件名操作
     * @param response HttpServletResponse
     * @param fileName 写出文件的文件名,若没有添加文件类型后缀,则默认添加".xls"
     */
    private static void fileNameHandle(HttpServletResponse response, String fileName) throws IOException{
        // 如果fileName没有".",说明没有加文件类型后缀,则默认添加".xls"
        if (fileName.indexOf(".") == -1) {
            fileName += ".xls";
        }
        // 文件名转码
        fileName = new String(fileName.getBytes(), "ISO-8859-1");
        // 在请求头中写入文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    }
    /**
     * 生成选择框限制
     * @param headers 标题行内容(用于确定,有选择框限制的列位置)
     * @param maps  需要做选择框限制的列的集合  说明:1.map中key为"titleContent"中需存入,需要做选择框的列顶部标题内容  2.map中key为"data"中需存入,所能选择的数据集合
     */
    private static void writeSelectionBox(String[] headers, List<Map<String, Object>> maps, HSSFWorkbook workbook) throws Exception{
        for(Map<String, Object> map : maps){
            // 需要做选择框限制的列的标题内容
            String titleContent = map.get("titleContent").toString();
            // 能选择的数据
            List<Object> list = (List<Object>) map.get("data");
            // 所能的数据不能超过50条(经过测试得出,超过50则会报错)
            if(list.size() > 50){
                throw new RuntimeException("所能选择的选项不能超过50");
            }
            // 确定有选择框限制的列位置
            Integer index = null;
            for(int i = 0; i < headers.length; ++i){
                if(headers[i].equals(titleContent)){
                    index = i;
                    break;
                }
            }
            // 如果确定不了位置,则弹出一个错误
            if(index == null){
                throw new RuntimeException("寻找不到指定列");
            }
            // 产生下拉框
            DVConstraint constraint1 = DVConstraint.createExplicitListConstraint(list.toArray(new String[list.size()]));
            // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
            CellRangeAddressList regions1 = new CellRangeAddressList(1, 500, 1, 1);
            // 数据有效性对象
            HSSFDataValidation data_validation_list1 = new HSSFDataValidation(regions1, constraint1);
            workbook.getSheetAt(0).addValidationData(data_validation_list1);
        }
    }

    /**
     * 写入标题行
     * @param headers 标题行内容
     * @param workbook HSSFWorkbook
     */
    private static void writeTitleRow(String[] headers, HSSFWorkbook workbook){
        // 获取表格
        HSSFSheet sheet = workbook.getSheetAt(0);
        // 生成标题样式
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        // 设置这些样式
        titleStyle.setBottomBorderColor(HSSFColor.SKY_BLUE.index);// 设置用于底部边框的颜色
        titleStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 设置前景色填充颜色注意:保证前颜色设置背景色。
        titleStyle.setFillBackgroundColor(HSSFColor.SKY_BLUE.index);// 设置背景填充颜色
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置为一个充满前景颜色的单元格
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置单元格的底边框的类型
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 设置单元格的左边框的类型
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 设置单元格的右边框的类型
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 设置单元格的顶边框的类型
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格的水平对齐方式
        // 生成标题字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);// 字体颜色
        font.setFontHeightInPoints((short) 12);// 字体高度
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字体粗细
        // 把标题字体应用到标题样式
        titleStyle.setFont(font);
        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
    }

    /**
     * 写入数据行
     * @param data 数据
     * @param workbook HSSFWorkbook
     */
    private static void writeDataRow(List<List<Object>> data, HSSFWorkbook workbook){
        // 获取表格
        HSSFSheet sheet = workbook.getSheetAt(0);
        // 生成并设置内容样式
        HSSFCellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        contentStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成内容字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        contentStyle.setFont(font2);
        int index = 0;
        for (List<Object> list : data) {
            index++;
            HSSFRow row = sheet.createRow(index);
            for (int i = 0; i < list.size(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(contentStyle);
                Object value = list.get(i);
                String textValue = null;
                if (value instanceof Boolean) {
                    boolean bValue = (Boolean) value;
                    textValue = "是";
                    if (!bValue) {
                        textValue = "否";
                    }
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    textValue = sdf.format(date);
                } else if (value instanceof byte[]) {
                    //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
                    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                    // 有图片时,设置行高为60px;
                    row.setHeightInPoints(60);
                    // 设置图片所在列宽度为80px,注意这里单位的一个换算
                    sheet.setColumnWidth(i, (short) (35.7 * 80));
                    byte[] bsValue = (byte[]) value;
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
                    anchor.setAnchorType(2);
                    //插入图片
                    patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                } else {
                    //其它数据类型都当作字符串简单处理
                    if (value != null) {
                        textValue = value.toString();
                    } else {
                        textValue = " ";
                    }
                }
                //如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                if (textValue != null) {
                    HSSFRichTextString richString = new HSSFRichTextString(textValue);
                    HSSFFont font3 = workbook.createFont();
                    richString.applyFont(font3);
                    cell.setCellValue(richString);
                }
            }
        }
    }
}

 

转载于:https://my.oschina.net/ljc94/blog/724495

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值