Java implements Excel export data

1. Introduce the org.apache.poi related jar package.
For details, see the previous article: Java implements Excel import data
2. Write Excel export method on the page (I use Layui component here), sample code:

var table = layui.table;
/********** (添加数据)表格头部工具栏监听事件  **********/
table.on('toolbar(insertInfo)', function(obj){
    
    
    var checkStatus = table.checkStatus(obj.config.id);
    var len = checkStatus.data.length;
    var count = obj.config.page.count;
    switch(obj.event){
    
    
      case 'export':
    	  var num=table.cache['insertInfo'].length;
    	  if(num==0){
    
    
    		  layer.msg('暂无可导出的数据');
    	  }else{
    
    
    		  layer.confirm('确定要导出当前的数据?', {
    
    
              	icon: 3,
                  btn: ['确定', '取消']
              }, function (index) {
    
    		
              	layer.close(index);
              	window.open("${ctx}/faultCode/exportToExcel.do?relevanceId=0");
  	   		});
    	  }
      break;
    };
});

3. The controller layer code is as follows:

/**
 * 导出Excel
 * @param response
 * @param session
 */
@SuppressWarnings("unchecked")
@ResponseBody
@RequestMapping("/exportToExcel")
@ApiOperation(value = "导出Excel", notes="导出故障码信息",httpMethod = "POST")
public void exportToExcel(Integer relevanceId, HttpServletResponse response, HttpSession session) {
    
    
	Map<String, Object> filedNames = new LinkedHashMap<String, Object>();
	String titleName = "";
	Class<?> objClass = null;
	Object obj = null;
	try {
    
    
		List<FaultCodeVo> listFault = null;
		//获取需要导出的数据,这里根据需要进行更改
		if (relevanceId == 0) {
    
    
			listFault = (List<FaultCodeVo>) session.getAttribute("listFault");
		} else {
    
    
			listFault = faultCodeService.selectFaultCodeById(relevanceId);
			List<FaultCodeVo> listFaultTwo = (List<FaultCodeVo>) session.getAttribute("listFaultTwo");
			if(listFaultTwo!=null) {
    
    
				listFault.addAll(listFaultTwo);
			}
		}
		if (listFault != null) {
    
    
			// 声明一个list集合接收Dao层查询所返回来的值
			obj = listFault;
			// excel标题和字段
			filedNames.put("dtc", "故障码\r\nDTC");
			filedNames.put("hexDtc", "故障码\r\n(hex)");
			filedNames.put("englishDescription", "故障码英文描述\r\nEnglish description");
			filedNames.put("chineseDescription", "故障码中文描述\r\nChinese description");
			filedNames.put("operatingConditions", "故障码运行条件\r\nDTC operating conditions");
			filedNames.put("settingConditions", "故障码设置条件\r\nDTC setting conditions");
			filedNames.put("settingAfterConditions", "故障码设置时发生的操作\r\nStrategy after DTC appears");
			filedNames.put("restoreConditions", "故障恢复条件\r\nDTC resume conditions");
			filedNames.put("activateMilRegulations", "激近故障灯原则\r\nActivate MIL regulations");
			filedNames.put("milOffRegulations", "熄灭故障灯原则\r\nMil Off regulations");
			filedNames.put("clearConditions", "清除故障码条件\r\nClear fault information conditions");
			titleName = "故障码信息表";
			objClass = FaultCodeVo.class;
			// 调用ExcelResponseUtil
			ExcelResponseUtil.exportToExcel(response, obj, filedNames, titleName, objClass);
		}
	} catch (Exception e) {
    
    
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

4. The following is the called tool class (ExcelResponseUtil), sample code:

package com.gx.util;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

@SuppressWarnings("all")
public class ExcelResponseUtil {
    
    

	/**
	 * 导出Excel
	 * 
	 * @param response
	 * @param list       导出数据集合
	 * @param filedNames excel标题&字段 此参数为map,实例为new LinkedHashMap<String, Object>();
	 * @param titleName  导出文件名
	 * @param objClass   实体类字节码.class
	 */
	public static void exportToExcel(HttpServletResponse response, Object list, Map<String, Object> filedNames,
			String titleName, Class<?> objClass) {
    
    
		// 第一步,创建一个webbook,对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet(titleName);
		// 设置列宽
		sheet.setColumnWidth(0, 15 * 256);
		sheet.setColumnWidth(1, 15 * 256);
		sheet.setColumnWidth(2, 36 * 256);
		sheet.setColumnWidth(3, 36 * 256);
		sheet.setColumnWidth(4, 36 * 256);
		sheet.setColumnWidth(5, 36 * 256);
		sheet.setColumnWidth(6, 36 * 256);
		sheet.setColumnWidth(7, 36 * 256);
		sheet.setColumnWidth(8, 36 * 256);
		sheet.setColumnWidth(9, 36 * 256);
		sheet.setColumnWidth(10, 36 * 256);
		// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		// 第四步,创建单元格,并设置值表头设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setWrapText(true);
		style.setAlignment(HorizontalAlignment.CENTER);
		// 声明列对象
		HSSFCell cell = null;
		Set<String> fileds = filedNames.keySet();
		try {
    
    
			int i = 0;
			// 创建标题
			for (String filed : fileds) {
    
    
				cell = row.createCell(i);
				cell.setCellValue(filedNames.get(filed).toString());
				cell.setCellStyle(style);
				i++;
			}
			if (list instanceof List) {
    
    
				List lists = (List) list;
				for (int j = 0; j < lists.size(); j++) {
    
    
					Object obj = objClass.newInstance();// 获取对象实例
					row = sheet.createRow(j + 1);
					
					obj = lists.get(j);// 获取一条数据
					int k = 0;
					for (String filed : fileds) {
    
    
						int num=0;
						String firstBig = filed.substring(0, 1).toUpperCase() + filed.substring(1);
						if(firstBig.equals("Name")) {
    
    
							num=1;
						}
						// ---获取getter方法,创建内容
						Method getMethod = objClass.getMethod("get" + firstBig);
						if(getMethod.invoke(obj)==null) {
    
    
							row.createCell(k).setCellValue("");
						}else {
    
    
							if(num>0) {
    
    
								String nameInfo=getMethod.invoke(obj).toString();
								String[] names=nameInfo.split(",");
								String info="";
								for (int l = 0; l < names.length; l++) {
    
    
									if(l==0) {
    
    
										info=names[l];
									}else {
    
    
										info=info+",\r\n"+names[l];
									}
								}
								row.createCell(k).setCellValue(info);
							}else {
    
    
								row.createCell(k).setCellValue(getMethod.invoke(obj).toString());
							}
						}
						row.getCell(k).setCellStyle(style);
						k++;
					}
				}
			}
			String fileName = "";// 文件名
			// 输出的文件名+以毫秒为单位返回当前时间
			// ISO8859-1不能改为UTF-8,否则文件名是乱码
			fileName = new String((titleName + System.currentTimeMillis() + ".xls").getBytes(), "ISO8859-1");
			// application应用;octet-stream八进制;charset字符集(请求应用)
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			// Content-Disposition内容配置;attachment附件;(下载完成提示)
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

5. The data to be exported and the exported Excel screenshot are as follows:
Data to be exported
Export Excel screenshot

Guess you like

Origin blog.csdn.net/weixin_44547592/article/details/111830272