JavaWeb 通用POI导出Excel

Controller层

@RequestMapping("")
@ResponseBody
public void export(HttpServletResponse response, String xxx){
    response.setContentType("text/html;charset=UTF-8");
    response.setContentType("multipart/form-data");
    try {
        response.setHeader("Content-disposition", "attachment; filename=" + new String("Excel名称.xls".getBytes("utf-8"), "ISO-8859-1"));
    } catch (UnsupportedEncodingException e1) {

        e1.printStackTrace();
    }
    BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(response.getOutputStream());
    } catch (IOException e) {

        e.printStackTrace();
    }
    String sheetName = "工作表名称";
    String titleName = "Title名称";
    String[] headers = {"姓名", "身份证号",  "工作单位及职务"}; // 表头
    String[] name = { "name", "idcard", "jobUnitAndPost"}; // 表头对应的字段名
    // 此list为导出数据
    List<Map<String, Object>> list = this.service.listPerson(xxx);
    // 此Map作第一行模版数据
    Map<String, Object> example = new HashMap<String, Object>(){{
        put("name", "张华");        
        put("idcard", "xxxxxxxxxxx");   
        put("jobUnitAndPost", "单位及职务名称");
    }};
    list.add(0, example);
    this.service.exportExcel(sheetName, titleName, headers, list, bos, name, 0);
    
}

Service层

public void exportExcel(String sheetName, String titleName, String[] headers, List<?> dataSet, BufferedOutputStream out, String[] name, int i) {
	doExportExcel(sheetName,titleName,headers,dataSet,out,name);
}
private void doExportExcel(String sheetName, String titleName, String[] headers, List<?> dataSet, BufferedOutputStream out, String[] name) {
	// 声明一个工作薄
	HSSFWorkbook workbook = new HSSFWorkbook();
	DataFormat fmt = workbook.createDataFormat();
	// 创建[标题]样式
	HSSFCellStyle titleStyle = workbook.createCellStyle();
	// 设置[标题]样式,水平居中
	titleStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
	titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	//创建[标题]字体
	HSSFFont titleFont = workbook.createFont();
	//设置[标题]字体
	titleFont.setFontHeightInPoints((short) 24);
	titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	// 把[标题字体]应用到[标题样式]
	titleStyle.setFont(titleFont);
	// 创建[列首]样式
	HSSFCellStyle headersStyle = workbook.createCellStyle();
	// 设置[列首]样式
	headersStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
	headersStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	//创建[标题]字体
	HSSFFont headersFont = workbook.createFont();
	//设置[标题]字体
	headersFont.setFontHeightInPoints((short) 12);
	headersFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	// 把[列首字体]应用到[列首样式]
	headersStyle.setFont(headersFont);
	// 创建[表中数据]样式
	HSSFCellStyle dataSetStyle = workbook.createCellStyle();
	// 设置[表中数据]样式
	dataSetStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	dataSetStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	dataSetStyle.setDataFormat(fmt.getFormat("@"));
	HSSFCellStyle cellStyle = workbook.createCellStyle();
	cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	// 居中 
	// 生成一个工作表
	HSSFSheet sheet = workbook.createSheet(sheetName);
    
	//在工作表中合并首行并居中
	sheet.addMergedRegion(new CellRangeAddress(0,0,0,headers.length-1));
	//创建<b>标题行</b>-增加样式-赋值
	HSSFRow titleRow = sheet.createRow(0);
	HSSFCell titleCell = titleRow.createCell(0);
	titleCell.setCellStyle(titleStyle);
	titleCell.setCellValue(titleName);
    
	// 创建列首-增加样式-赋值    (若不想要标题栏,可删除上方法)
	HSSFRow row = sheet.createRow(1); // 起始行,因为有标题,所以在第二行
	for (short i = 0; i < headers.length; i++) {
		@SuppressWarnings("deprecation")
		        HSSFCell cell = row.createCell(i);
		cell.setCellStyle(headersStyle);
		HSSFRichTextString text = new HSSFRichTextString(headers[i]);
		cell.setCellValue(text);
	}
	// 创建表中数据行-增加样式-赋值
	Iterator<?> it = dataSet.iterator();
	int index = 0;
	while (it.hasNext()) {
		index++;
		row = sheet.createRow(index);
		Map<String ,Object> t = (Map<String, Object>) it.next();
		for (int k=0;k<name.length;k++){
			@SuppressWarnings("deprecation")
			                         HSSFCell cell = row.createCell(k);
			String textValue ="";
			if(t.containsKey(name[k])){
				textValue = t.get(name[k]).toString();
			}
			cell.setCellValue(textValue);
			cellStyle.setWrapText(true);
			cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			//垂直
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			//水平
			cellStyle.setDataFormat(fmt.getFormat("@"));
			cell.setCellStyle(cellStyle);
		}
	}
    
    // 单元格下拉样式,这里只定义了一个。(扩展:从Controller、service传多个[],此处拆分,组合)
	String[] strs = { "日常考察", "专项考察", "跟踪考察", "延伸考察", "推荐考察", "任职考察", "其他考察" };
	// 四个参数分别是:起始行、终止行、起始列、终止列
	CellRangeAddressList regions = new CellRangeAddressList(1, dataSet.size() + 1, 4, 4);
	DVConstraint constraint = DVConstraint.createExplicitListConstraint(strs);
	HSSFDataValidation dataValidation = new HSSFDataValidation(regions,constraint);
	sheet.addValidationData(dataValidation);
    // 定义列宽度(可根据headers循环添加固定宽度)
	sheet.setColumnWidth(0, 3000);
	sheet.setColumnWidth(1, 5500);
	sheet.setColumnWidth(2, 9000);
	sheet.setColumnWidth(3, 6500);
	sheet.setColumnWidth(4, 6000);
	sheet.setColumnWidth(5, 6000);
	try {
		workbook.write(out);
	}
	catch (IOException e) {
    
	}
	finally{
		try {
			out.close();
		}
		catch (IOException e) {
        
		}
	}
}
上一篇:解决java poi导出excel2003不能超过65536行的问题


下一篇:c# winform ListView导出Excel(2017)