excel的導入導出
阿新 • • 發佈:2018-07-31
ORC rim valueof img pro n) hashmap ray trace
引入js包
ExcelUtil.java
package com.guilf.consumer.excel; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.poi.POIXMLDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; 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.ss.util.NumberToTextConverter; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.util.StringUtils; /** * EXCEL導入工具類 */ public class ExcelUtil { /** * 將導入的EXCEL轉化為LIST數組 * * @param inputStream * 文件輸入流 * @param startRow * 記錄起始行 * @param dataLen * 記錄所占列數 * @return list數組 * @throws IOException * @throws InvalidFormatException */ public static List<String[]> readExcel(InputStream inputStream, int startRow, int dataLen) throws IOException, InvalidFormatException { Workbook workbook = getWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); return getDataList(startRow, dataLen, sheet); } private static List<String[]> getDataList(int startRow, int dataLen, Sheet sheet) { int rowNum = sheet.getLastRowNum(); List<String[]> list = new ArrayList<String[]>(); // 從第三行開始讀 for (int i = startRow; i <= rowNum; i++) { Row row = sheet.getRow(i); String dataArr[] = new String[dataLen]; StringBuilder sb = new StringBuilder(0); for (int j = 0; j < dataLen; j++) { String data = ""; Cell cell = row.getCell(j); if (null == cell) { continue; } switch (cell.getCellType()) { case Cell.CELL_TYPE_ERROR:{ byte errorValue = cell.getErrorCellValue(); System.out.println(errorValue); break; } case Cell.CELL_TYPE_FORMULA: try { data=cell.getStringCellValue(); } catch (Exception e){ data=""; } if(StringUtils.isEmpty(data)){ try{ data = NumberToTextConverter.toText(cell.getNumericCellValue()); } catch (Exception e){ data=""; } } if(StringUtils.isEmpty(data)){ try { cell.setCellType(Cell.CELL_TYPE_STRING); data=String.valueOf(cell.getStringCellValue()); data=data.replace("#N/A", ""); } catch (Exception e) { data=""; } } break; case Cell.CELL_TYPE_STRING: data = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: data = NumberToTextConverter.toText(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: data = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_BLANK: data = ""; break; default: data = ""; break; } if (isTrimEmpty(data)) { data = ""; } dataArr[j] = data; sb.append(data); } if (isTrimEmpty(sb.toString()))// 如果空行則跳出,說明該行無數據 { break; } list.add(dataArr); } return list; } private static boolean isTrimEmpty(String s) { return ((s == null) || (s.trim().isEmpty())); } private static Workbook getWorkbook(InputStream inputStream) throws IOException, InvalidFormatException { Workbook workbook; if (!inputStream.markSupported()) { inputStream = new PushbackInputStream(inputStream, 8); } if (POIXMLDocument.hasOOXMLHeader(inputStream)) { workbook = new XSSFWorkbook(OPCPackage.open(inputStream)); } else { workbook = new HSSFWorkbook(inputStream); } inputStream.close(); return workbook; } public static void main(String[] args) { String str = "E:\\Temp\\aa.xls"; try { FileInputStream inputStream = new FileInputStream(str); List<String[]> list = ExcelUtil.readExcel(inputStream, 3, 15); System.out.println(JSONObject.toJSONString(list)); } catch (Exception e) { e.printStackTrace(); } } }
SimpleExportExcelUtil.java
package com.guilf.consumer.excel; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; public class SimpleExportExcelUtil { public static void exportExcel(String sheetTitle, String[] attrNames, List<?> dataList, HttpServletRequest request, HttpServletResponse response, String[] HEADERS, String[] NEXT_HEADERS, String fileName, String[] lastRow) { OutputStream outputStream = null; try { response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls"); outputStream = response.getOutputStream(); HSSFWorkbook workbook = assemberWorkbook(sheetTitle, attrNames, dataList, response, HEADERS, NEXT_HEADERS, lastRow); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } request.getSession().removeAttribute("flag"); System.gc(); } } private static HSSFWorkbook assemberWorkbook(String sheetTitle, String[] attrNames, List<?> dataList, HttpServletResponse response, String[] HEADERS, String[] NEXT_HEADERS, String[] lastRow) { // 聲明一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); int dsize = dataList.size(); int size = dsize % 20000 == 0 ? dsize / 20000 : dsize / 20000 + 1; if ((0==size)||(1==size)) { data(workbook, sheetTitle, attrNames, dataList, response, HEADERS, NEXT_HEADERS, lastRow); } else { List<Object> sds = new ArrayList<Object>(); for (int i = 1; i <= size; i++) { if (i == size) { for (int j = 0; j < dsize - (size - 1) * 20000; j++) { sds.add(dataList.get(j + (size - 1) * 20000)); } } else { for (int j = 0; j < 20000; j++) { sds.add(dataList.get(j + 20000 * (i - 1))); } } data(workbook, sheetTitle + i, attrNames, sds, response, HEADERS, NEXT_HEADERS, lastRow); sds.removeAll(sds); } } return workbook; } // 一個excel表生成多張表格的 public static void exportExcelMoreSheet(HttpServletRequest request,HttpServletResponse response, List<Map<String, Object>> listMap, String fileName) { OutputStream outputStream = null; try { response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls"); outputStream = response.getOutputStream(); // 聲明一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); workbook = assemberWorkbookMoreSheet(workbook, response, listMap); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } request.getSession().removeAttribute("flag"); System.gc(); } } @SuppressWarnings("unchecked") private static HSSFWorkbook assemberWorkbookMoreSheet(HSSFWorkbook workbook, HttpServletResponse response, List<Map<String, Object>> listMap) { for(int k = 0; k<listMap.size(); k++){ List<?> dataList = (List<Map<String, Object>>) listMap.get(k).get("dataList"); String sheetTitle = (String) listMap.get(k).get("sheetTitle"); String[] attrNames=(String[]) listMap.get(k).get("attrNames"); String[] HEADERS=(String[]) listMap.get(k).get("headers"); String[] NEXT_HEADERS=(String[]) listMap.get(k).get("nextHeaders"); String[] lastRow=(String[]) listMap.get(k).get("lastRow"); int dsize; if(dataList == null || dataList.size() == 0) { dataList = new ArrayList<Map<String,Object>>(); dsize = 0 ; } else{ dsize = dataList.size(); } int size = dsize % 20000 == 0 ? dsize / 20000 : dsize / 20000 + 1; if ((0==size)||(1==size)) { int n = 0; for(int m=0; m<k; m++) { if(Objects.equals(sheetTitle, listMap.get(m).get("sheetTitle"))){ n++; } } if(n != 0){ data(workbook, sheetTitle+"-"+n, attrNames, dataList, response, HEADERS, NEXT_HEADERS, lastRow); } else{ data(workbook, sheetTitle, attrNames, dataList, response, HEADERS, NEXT_HEADERS, lastRow); } } else { List<Object> sds = new ArrayList<Object>(); for (int i = 1; i <= size; i++) { if (i == size) { for (int j = 0; j < dsize - (size - 1) * 20000; j++) { sds.add(dataList.get(j + (size - 1) * 20000)); } } else { for (int j = 0; j < 20000; j++) { sds.add(dataList.get(j + 20000 * (i - 1))); } } data(workbook, sheetTitle+i, attrNames, sds, response, HEADERS, NEXT_HEADERS, lastRow); sds.removeAll(sds); } } } return workbook; } private static HSSFCellStyle createHeaderCellStyle(HSSFWorkbook workbook) { // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設置這些樣式 // style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); // style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // style.setBorderRight(HSSFCellStyle.BORDER_THIN); // style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } private static HSSFCellStyle createBodyCellStyle(HSSFWorkbook workbook) { // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設置這些樣式 // style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); // style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // style.setBorderRight(HSSFCellStyle.BORDER_THIN); // style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } private static HSSFFont createHeaderFont(HSSFWorkbook workbook) { // 生成一個字體 HSSFFont font = workbook.createFont(); // font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 10); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); return font; } private static HSSFFont createBodyFont(HSSFWorkbook workbook) { // 生成一個字體 HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); return font; } @SuppressWarnings({"deprecation"}) private static void data(HSSFWorkbook workbook, String sheetTitle, String[] attrNames, List<?> dataList, HttpServletResponse response, String[] HEADERS, String[] NEXT_HEADERS, String[] lastRow) { // 生成一個表格 HSSFSheet sheet =workbook.createSheet(sheetTitle); // 設置表格默認列寬度為15個字節 sheet.setDefaultColumnWidth((short) 15); HSSFCellStyle headerStyle = createHeaderCellStyle(workbook); // 把字體應用到當前的樣式 headerStyle.setFont(createHeaderFont(workbook)); HSSFCellStyle bodyStyle = createBodyCellStyle(workbook); // 把字體應用到當前的樣式 bodyStyle.setFont(createBodyFont(workbook)); // 聲明一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文檔 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設置註釋內容 comment.setString(new HSSFRichTextString("我的鋼鐵(www.mysteel.com)")); // 設置註釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容. comment.setAuthor("mysteel"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); row.setHeight((short) 400); int headrow = 1; if (HEADERS != null) { for (short i = 0; i < HEADERS.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(headerStyle); cell.setCellValue(new HSSFRichTextString(HEADERS[i])); } // 合並表頭單元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, NEXT_HEADERS.length - 1)); headrow = 2; } // 產生表格次標題行 HSSFRow row2 = sheet.createRow(headrow - 1); row2.setHeight((short) 400); HSSFCell cell = null; for (short i = 0; i < NEXT_HEADERS.length; i++) { cell = row2.createCell(i); cell.setCellStyle(headerStyle); cell.setCellValue(new HSSFRichTextString(NEXT_HEADERS[i])); } Pattern p = Pattern.compile("^//d+(//.//d+)?$"); // 遍歷集合數據,產生數據行 for (int i = 0; i < dataList.size(); i++) { row = sheet.createRow(i + headrow); @SuppressWarnings({"unchecked", "rawtypes"}) Map<String, Object> map = (Map) dataList.get(i); //obj = dataList.get(i); // 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值 for (short j = 0; j < attrNames.length; j++) { cell = row.createCell(j); cell.setCellStyle(bodyStyle); String fieldName = attrNames[j]; /*String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);*/ try { /*Method method = obj.getClass().getMethod(methodName, new Class[] {});*/ //Object value = method.invoke(obj, new Object[] {}); Object value = map.get(fieldName); // 判斷值的類型後進行強制類型轉換 String textValue = null; if (value != null) { if (value instanceof Boolean) { // } else if (value instanceof Date) { //textValue = DateTool.formatJustDate(((Date) value).getTime()); } else if (value instanceof byte[]) { // 有圖片時,設置行高為60px; row.setHeightInPoints(60); // 設置圖片所在列寬度為80px,註意這裏單位的一個換算 sheet.setColumnWidth(j, (short) (35.7 * 100)); // sheet.autoSizeColumn(i); byte[] byteValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, i + 1, (short) 6, i + 1); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook .addPicture(byteValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { // 其它數據類型都當作字符串簡單處理 textValue = value.toString(); } } // 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成 if (textValue != null) { if (p.matcher(textValue).matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { cell.setCellValue(textValue); } } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } finally { // 清理資源 } } } if (lastRow != null && lastRow.length > 0) { row = sheet.createRow(dataList.size() + headrow); cell = row.createCell(0); cell.setCellStyle(headerStyle); cell.setCellValue("合計:"); int index = 0; for (int j = 1; j < NEXT_HEADERS.length; j++) { if (j >= NEXT_HEADERS.length - lastRow.length) { cell = row.createCell(j); cell.setCellStyle(headerStyle); cell.setCellValue(lastRow[index]); index++; } else { cell = row.createCell(j); } } } } // private static HSSFSheet createSheet(HSSFWorkbook workbook, String sheetTitle, String[] header) // { // HSSFSheet sheet = workbook.createSheet(sheetTitle); // sheet.setDefaultColumnWidth(12); // sheet.setColumnWidth(0, 6000); // sheet.setColumnWidth(1, 6000); // sheet.setColumnWidth(2, 5000); // sheet.setColumnWidth(3, 5000); // sheet.setColumnWidth(4, 5000); // sheet.setColumnWidth(10, 6000); // sheet.setColumnWidth(14, 5000); // // HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // comment.setString(new HSSFRichTextString("我的鋼鐵(www.mysteel.com)")); // comment.setAuthor("Mysteel"); // // HSSFFont font = createHeaderFont(workbook); // HSSFCellStyle style = createHeaderCellStyle(workbook); // style.setFont(font); // HSSFRow row = sheet.createRow(0); // row.setHeight((short)400); // // for (int i = 0; i < header.length; i++) // { // HSSFCell cell = row.createCell(i); // cell.setCellStyle(style); // cell.setCellValue(new HSSFRichTextString(header[i])); // } // // return sheet; // } }
vm頁面
<label class="btn btn-default" id="labelClick" for="uploadApplyItemData">導入數據</label> <input id="uploadApplyItemData" type="file" name="uploadFile" accept="*.xls" value="導入數據"/>
js
//異步上傳excel文件 $(‘#uploadApplyItemData‘).fileupload({ url:‘uploading.do‘, dataType:‘json‘, type:‘post‘, done: function (e, res) { var dataList = res.result.data; $(‘#myExcelIn‘).find(‘tr‘).remove(); $(dataList).each(function(i, data){ getContentHtml(); var tr = $(‘#myExcelIn‘).find(‘tr‘)[i]; var tds = $(tr).find("td"); $(tds[0]).text(data[0]); $(tds[1]).text(data[1]); }); }, fail:function (e, data){ var a=1; } });
java
package com.guilf.consumer.controller; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSONObject; import com.guilf.consumer.excel.ExcelUtil; import com.guilf.consumer.excel.SimpleExportExcelUtil; //import com.guilf.project.entity.User; //import com.guilf.project.service.UserService; @Controller("excelController") @RequestMapping("/") public class ExcelController { //@Autowired //private UserService userService; @RequestMapping("excel") public String hello(){ return "excelInAndOut"; } // excel導入 @RequestMapping(value="uploading",method=RequestMethod.POST) @ResponseBody public Object uploadExcel( HttpServletRequest request, HttpServletResponse response, @RequestParam("uploadFile") MultipartFile uploadFile ) throws Exception { if((null!=uploadFile)&&(!(uploadFile.getOriginalFilename().endsWith(".xls")|| uploadFile.getOriginalFilename().endsWith(".xlsx")))){ throw new Exception("導入文件類型錯誤!"); } JSONObject rejson = new JSONObject(); try { //HttpServletRequest request, HttpServletResponse response, List<String[]> list=ExcelUtil.readExcel(uploadFile.getInputStream(), 0, 2); //List<Object> ret=importAo.check(list, 3); rejson.put("data", list); } catch (Exception e) { e.printStackTrace(); throw new Exception(e.getMessage()); } String userAgent = request.getHeader("User-Agent"); if (userAgent.contains("MSIE 9")) { response.setContentType("text/plain"); return rejson.toJSONString(); } return rejson; } //excel導出 @SuppressWarnings("unchecked") @RequestMapping("excelOut") public void excelOut(HttpServletRequest request, HttpServletResponse response) throws Exception { try { Map<String, Object> map = exportOrder(); String sheetTitle=(String) map.get("sheetTitle"); String[] attrNames=(String[]) map.get("attrNames"); String[] headers=(String[]) map.get("headers"); List<Map<String, Object>> dataList = (List<Map<String, Object>>) map.get("dataList"); SimpleExportExcelUtil.exportExcel(sheetTitle, attrNames, dataList, request, response, null, headers, URLEncoder.encode("我的導出excel", "utf-8"), null); } catch (Exception e) { e.printStackTrace(); throw new Exception(e.getMessage()); } } private Map<String, Object> exportOrder() throws Exception { Map<String, Object> result = new HashMap<String, Object>(); String sheetTitle = "我的導出excel"; String[] attrNames = {"第一值", "第二值"}; String[] NEXT_HEADERS = {"第一值", "第二值"}; result.put("sheetTitle", sheetTitle); result.put("attrNames", attrNames); result.put("headers", NEXT_HEADERS); List<Map<String, Object>> dataList = listOrderMap(); result.put("dataList", dataList); return result; } private List<Map<String, Object>> listOrderMap() { // 查詢訂單信息 List<Map<String,Object>> listExcel = new ArrayList<Map<String,Object>>(); for(int i=0 ;i<7; i++) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("第一值", "dd"+i); paramMap.put("第二值", "rr"+i); listExcel.add(paramMap); } return listExcel; } }
excel的導入導出