package com.walmart.aloha.productmanage.util; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; public class ExcleUtils { private static final Logger logger = LoggerFactory.getLogger(ExcleUtils.class); public static void setCellValue(int index, String strValue, XSSFRow row) { XSSFCell cell; cell = row.createCell(index); cell.setCellValue( strValue ); } public static void setTitle(int[] colwidth1, String[] title, XSSFWorkbook wb, XSSFSheet sheet) { for (int i = 0; i < colwidth1.length; i++) { sheet.setColumnWidth(i, colwidth1[i]); } // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 XSSFRow row = sheet.createRow(0); // 第四步,创建单元格,并设置值表头 设置表头居中 XSSFCellStyle cellstyle = wb.createCellStyle(); // 创建垂直一个居中格式 cellstyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式 cellstyle.setVerticalAlignment(VerticalAlignment.CENTER); Font titlefont = wb.createFont(); titlefont.setBold(true); titlefont.setFontName("宋体"); cellstyle.setFont(titlefont); //声明列对象 XSSFCell cell = null; //创建标题 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(cellstyle); } } //发送响应流方法 public static void setResponseHeader(HttpServletResponse response, String fileName) { try { response.reset(); response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); String name = URLEncoder.encode(fileName, "UTF-8"); //解决文件名乱码的问题 fileName = new String(name.getBytes("utf-8"), "ISO-8859-1"); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentType("application/octet-stream"); response.setCharacterEncoding("UTF-8"); } catch (Exception ex) { logger.error("Exception", ex); } } /** * 写出文件 2007 */ public static void writeXssfFile(HttpServletResponse response, HttpServletRequest request, XSSFWorkbook wb, String fileName) { try { ExcleUtils.setResponseHeader(response, fileName); OutputStream os = new BufferedOutputStream(response.getOutputStream()); wb.write(os); os.flush(); os.close(); } catch (Exception e) { logger.error("Exception ", e); e.printStackTrace(); } } //写出文件 2003 public static void writeFile(HttpServletResponse response, HttpServletRequest request, HSSFWorkbook wb, String fileName) { try { final String userAgent = request.getHeader("USER-AGENT"); String finalFileName = null; if (StringUtils.contains(userAgent, "MSIE")) {//IE浏览器 finalFileName = URLEncoder.encode(fileName, "UTF8"); } else if (StringUtils.contains(userAgent, "Mozilla")) {//google,火狐浏览器 finalFileName = new String(fileName.getBytes(), "ISO8859-1"); } else { finalFileName = URLEncoder.encode(fileName, "UTF8");//其他浏览器 } ExcleUtils.setResponseHeader(response, finalFileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { logger.error("Exception ", e); e.printStackTrace(); } } /** * 获取workbook * * @param file * @param excelName * @return * @throws IOException */ public static Workbook getWorkBook(MultipartFile file, String excelName) throws IOException { InputStream is = null; is = file.getInputStream(); Workbook wb = null; if (excelName.toLowerCase().endsWith("xls")) { // Excel-2003 wb = new HSSFWorkbook(is); } else if (excelName.toLowerCase().endsWith("xlsx")) { // Excel-2007 wb = new XSSFWorkbook(is); } return wb; } }
方法用户的导出功能 导出为 xlsx格式
@Override public void exportByWhere(ParamUser paramUser, HttpServletResponse response, HttpServletRequest request) { List<UserInfo> list = userInfoMapper.exportByWhere(paramUser); int[] colwidth1 = {20 * 256, 20 * 256, 20 * 256, 40 * 256, 40 * 256, 30 * 256, 20 * 256, 20 * 256}; String[] title = {"Domain", "Team", "Role", "Name", "Mobile number", "User ID", " 工号 ", "Supervisor", "Status(在职/离职)"}; String sheetName = "User List"; XSSFWorkbook wb = new XSSFWorkbook(); // 创建一个工作薄对象 XSSFSheet sheet = wb.createSheet(sheetName); ExcleUtils.setTitle(colwidth1, title, wb, sheet); XSSFRow row; for (int i = 0; i < list.size(); i++) { UserInfo userInfo = list.get(i); row = sheet.createRow(i + 1); ExcleUtils.setCellValue(0, BaseInfo.isNull(userInfo.getDomain()), row); ExcleUtils.setCellValue(1, BaseInfo.isNull(userInfo.getTeam()), row); ExcleUtils.setCellValue(2, BaseInfo.isNull(userInfo.getRole()), row); ExcleUtils.setCellValue(3, BaseInfo.isNull(userInfo.getEnglishName()), row); ExcleUtils.setCellValue(4, BaseInfo.isNull(userInfo.getMobileNum()), row); ExcleUtils.setCellValue(5, BaseInfo.isNull(userInfo.getUserId()), row); ExcleUtils.setCellValue(6, BaseInfo.isNull(userInfo.getEmpId() == null ? "-" : userInfo.getEmpId()), row); ExcleUtils.setCellValue(7, BaseInfo.isNull(userInfo.getSuperiorEnglishName()), row); ExcleUtils.setCellValue(8, BaseInfo.isNull(userInfo.getStatus()), row); } String fileName = "user_list" + System.currentTimeMillis() + ".xlsx"; ExcleUtils.writeXssfFile(response, request, wb, fileName); }