在SSM下使用POI实现Excel表的导入/导出

导出就是将List转化为ExcellistToExcel

导入就是将Excel转化为ListexcelToList

POI

Apache POIApache软件基金会的开放源码函式库,POI提供APIJava程序对Microsoft Office格式档案读和写的功能。

我们知道要创建一张excel你得知道excel由什么组成,比如说sheet也就是一个工作表格,例如一行,一个单元格,单元格格式,单元格内容格式…这些都对应着poi里面的一个类。

一个excel表格:

HSSFWorkbook wb = new HSSFWorkbook();

一个工作表格(sheet):

HSSFSheet sheet = wb.createSheet("测试表格");

一行(row):

HSSFRow row1 = sheet.createRow(0);

一个单元格(cell):

HSSFCell cell2 = row2.createCell((short)0)

单元格格式(cellstyle):

HSSFCellStyle style4 = wb.createCellStyle()

单元格内容格式()

HSSFDataFormat format= wb.createDataFormat();

知道上面的基本知识后下面学起来就轻松了

poi批量导入导出的jar

http://pan.baidu.com/s/1o7CsH78

poi-ooxml-3.13.jar

poi-ooxml-schemas-3.13.jar

poi-3.13.jar

xmlbeans-2.6.0.jar

fastjson-1.2.2-sources.jar

fastjson-1.2.2.jar

创建一个Excel表数据导入和导出的工具类ExcelUtil

http://pan.baidu.com/s/1c2vYsog

[java]  view plain  copy
  1. package com.city.pms.common.utils;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.math.BigDecimal;  
  11. import java.text.DecimalFormat;  
  12. import java.text.SimpleDateFormat;  
  13. import java.util.ArrayList;  
  14. import java.util.Date;  
  15. import java.util.Iterator;  
  16. import java.util.List;  
  17. import java.util.Map;  
  18.   
  19. import javax.servlet.ServletOutputStream;  
  20. import javax.servlet.http.HttpServletResponse;  
  21.   
  22. import org.apache.poi.hssf.usermodel.HSSFCell;  
  23. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  24. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;  
  25. import org.apache.poi.hssf.usermodel.HSSFComment;  
  26. import org.apache.poi.hssf.usermodel.HSSFFont;  
  27. import org.apache.poi.hssf.usermodel.HSSFPatriarch;  
  28. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  29. import org.apache.poi.hssf.usermodel.HSSFRow;  
  30. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  31. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  32. import org.apache.poi.ss.usermodel.Cell;  
  33. import org.apache.poi.ss.usermodel.CellStyle;  
  34. import org.apache.poi.ss.usermodel.Font;  
  35. import org.apache.poi.ss.usermodel.Row;  
  36. import org.apache.poi.ss.usermodel.Sheet;  
  37. import org.apache.poi.ss.usermodel.Workbook;  
  38. import org.apache.poi.xssf.streaming.SXSSFCell;  
  39. import org.apache.poi.xssf.streaming.SXSSFRow;  
  40. import org.apache.poi.xssf.streaming.SXSSFSheet;  
  41. import org.apache.poi.xssf.streaming.SXSSFWorkbook;  
  42. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  43.   
  44. import com.alibaba.fastjson.JSONArray;  
  45. import com.alibaba.fastjson.JSONObject;  
  46.   
  47. public class ExcellUtil{  
  48.       
  49.     public static String NO_DEFINE = "no_define";//未定义的字段  
  50.     public static String DEFAULT_DATE_PATTERN="yyyy-MM-dd";//默认日期格式  
  51.     public static int DEFAULT_COLOUMN_WIDTH = 17;  
  52.       
  53.     private final static String excel2003L =".xls";    //2003- 版本的excel    
  54.     private final static String excel2007U =".xlsx";   //2007+ 版本的excel    
  55.     /**  
  56.      * Excel导入 
  57.      */    
  58.     public static  List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{    
  59.         List<List<Object>> list = null;    
  60.         //创建Excel工作薄    
  61.         Workbook work = getWorkbook(in,fileName);    
  62.         if(null == work){    
  63.             throw new Exception("创建Excel工作薄为空!");    
  64.         }    
  65.         Sheet sheet = null;    
  66.         Row row = null;    
  67.         Cell cell = null;    
  68.         list = new ArrayList<List<Object>>();    
  69.         //遍历Excel中所有的sheet    
  70.         for (int i = 0; i < work.getNumberOfSheets(); i++) {    
  71.             sheet = work.getSheetAt(i);    
  72.             if(sheet==null){continue;}    
  73.             //遍历当前sheet中的所有行    
  74.             //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部    
  75.             for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {    
  76.                 //读取一行    
  77.                 row = sheet.getRow(j);    
  78.                 //去掉空行和表头    
  79.                 if(row==null||row.getFirstCellNum()==j){continue;}    
  80.                 //遍历所有的列    
  81.                 List<Object> li = new ArrayList<Object>();    
  82.                 for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {    
  83.                     cell = row.getCell(y);    
  84.                     li.add(getCellValue(cell));    
  85.                 }    
  86.                 list.add(li);    
  87.             }    
  88.         }    
  89.         return list;    
  90.     }    
  91.     /**  
  92.      * 描述:根据文件后缀,自适应上传文件的版本  
  93.      */    
  94.     public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{    
  95.         Workbook wb = null;    
  96.         String fileType = fileName.substring(fileName.lastIndexOf("."));    
  97.         if(excel2003L.equals(fileType)){    
  98.             wb = new HSSFWorkbook(inStr);  //2003-    
  99.         }else if(excel2007U.equals(fileType)){    
  100.             wb = new XSSFWorkbook(inStr);  //2007+    
  101.         }else{    
  102.             throw new Exception("解析的文件格式有误!");    
  103.         }    
  104.         return wb;    
  105.     }    
  106.     /**  
  107.      * 描述:对表格中数值进行格式化  
  108.      */    
  109.     public static  Object getCellValue(Cell cell){    
  110.         Object value = null;    
  111.         DecimalFormat df = new DecimalFormat("0");  //格式化字符类型的数字    
  112.         SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化    
  113.         DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字    
  114.         switch (cell.getCellType()) {    
  115.             case Cell.CELL_TYPE_STRING:    
  116.                 value = cell.getRichStringCellValue().getString();    
  117.                 break;    
  118.             case Cell.CELL_TYPE_NUMERIC:    
  119.                 if("General".equals(cell.getCellStyle().getDataFormatString())){    
  120.                     value = df.format(cell.getNumericCellValue());    
  121.                 }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){    
  122.                     value = sdf.format(cell.getDateCellValue());    
  123.                 }else{    
  124.                     value = df2.format(cell.getNumericCellValue());    
  125.                 }    
  126.                 break;    
  127.             case Cell.CELL_TYPE_BOOLEAN:    
  128.                 value = cell.getBooleanCellValue();    
  129.                 break;    
  130.             case Cell.CELL_TYPE_BLANK:    
  131.                 value = "";    
  132.                 break;    
  133.             default:    
  134.                 break;    
  135.         }    
  136.         return value;    
  137.     }    
  138.       
  139.       
  140.     /** 
  141.      * 导出Excel 97(.xls)格式 ,少量数据 
  142.      * @param title 标题行  
  143.      * @param headMap 属性-列名 
  144.      * @param jsonArray 数据集 
  145.      * @param datePattern 日期格式,null则用默认日期格式 
  146.      * @param colWidth 列宽 默认 至少17个字节 
  147.      * @param out 输出流 
  148.      */  
  149.     public static void exportExcel(Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {  
  150.         if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;  
  151.         // 声明一个工作薄  
  152.         HSSFWorkbook workbook = new HSSFWorkbook();  
  153.         workbook.createInformationProperties();  
  154.         workbook.getDocumentSummaryInformation().setCompany("*****公司");  
  155.           
  156.          //表头样式  
  157.         HSSFCellStyle titleStyle = workbook.createCellStyle();  
  158.         titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  159.         HSSFFont titleFont = workbook.createFont();  
  160.         titleFont.setFontHeightInPoints((short20);  
  161.         titleFont.setBoldweight((short700);  
  162.         titleStyle.setFont(titleFont);  
  163.           
  164.         // 列头样式  
  165.         HSSFCellStyle headerStyle = workbook.createCellStyle();  
  166.         headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  167.         headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  168.         headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  169.         headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  170.         headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  171.         headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  172.         headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  173.         HSSFFont headerFont = workbook.createFont();  
  174.         headerFont.setFontHeightInPoints((short12);  
  175.         headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  176.         headerStyle.setFont(headerFont);  
  177.           
  178.         // 单元格样式  
  179.         HSSFCellStyle cellStyle = workbook.createCellStyle();  
  180.         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  181.         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  182.         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  183.         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  184.         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  185.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  186.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  187.         HSSFFont cellFont = workbook.createFont();  
  188.         cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  189.         cellStyle.setFont(cellFont);  
  190.           
  191.         // 生成一个(带标题)表格  
  192.         HSSFSheet sheet = workbook.createSheet();  
  193.         // 声明一个画图的顶级管理器  
  194.         HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
  195.         // 定义注释的大小和位置,详见文档  
  196.         HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,  
  197.                 000, (short42, (short65));  
  198.         // 设置注释内容  
  199.         comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));  
  200.         // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.  
  201.         comment.setAuthor("JACK");  
  202.         //设置列宽  
  203.         int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数  
  204.         int[] arrColWidth = new int[headMap.size()];  
  205.         // 产生表格标题行,以及设置列宽  
  206.         String[] properties = new String[headMap.size()];  
  207.         String[] headers = new String[headMap.size()];  
  208.         int ii = 0;  
  209.         for (Iterator<String> iter = headMap.keySet().iterator(); iter  
  210.                 .hasNext();) {  
  211.             String fieldName = iter.next();  
  212.   
  213.             properties[ii] = fieldName;  
  214.             headers[ii] = fieldName;  
  215.   
  216.             int bytes = fieldName.getBytes().length;  
  217.             arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;  
  218.             sheet.setColumnWidth(ii,arrColWidth[ii]*256);  
  219.             ii++;  
  220.         }  
  221.         // 遍历集合数据,产生数据行  
  222.         int rowIndex = 0;  
  223.         for (Object obj : jsonArray) {  
  224.             if(rowIndex == 65535 || rowIndex == 0){  
  225.                 if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示  
  226.   
  227.                 HSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =0  
  228.                 for(int i=0;i<headers.length;i++)  
  229.                 {  
  230.                     headerRow.createCell(i).setCellValue(headers[i]);  
  231.                     headerRow.getCell(i).setCellStyle(headerStyle);  
  232.   
  233.                 }  
  234.                 rowIndex = 1;//数据内容从 rowIndex=1开始  
  235.             }  
  236.             JSONObject jo = (JSONObject) JSONObject.toJSON(obj);  
  237.             HSSFRow dataRow = sheet.createRow(rowIndex);  
  238.             for (int i = 0; i < properties.length; i++)  
  239.             {  
  240.                 HSSFCell newCell = dataRow.createCell(i);  
  241.   
  242.                 Object o =  jo.get(properties[i]);  
  243.                 String cellValue = "";   
  244.                 if(o==null) cellValue = "";  
  245.                 else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);  
  246.                 else cellValue = o.toString();  
  247.   
  248.                 newCell.setCellValue(cellValue);  
  249.                 newCell.setCellStyle(cellStyle);  
  250.             }  
  251.             rowIndex++;  
  252.         }  
  253.         // 自动调整宽度  
  254.         /*for (int i = 0; i < headers.length; i++) { 
  255.             sheet.autoSizeColumn(i); 
  256.         }*/  
  257.         try {  
  258.             workbook.write(out);  
  259.             workbook.close();  
  260.         } catch (IOException e) {  
  261.             e.printStackTrace();  
  262.         }  
  263.     }  
  264.       
  265.     /** 
  266.      * 导出Excel 2007 OOXML (.xlsx)格式 
  267.      * @param title 标题行 
  268.      * @param headMap 属性-列头 
  269.      * @param jsonArray 数据集 
  270.      * @param datePattern 日期格式,传null值则默认 年月日 
  271.      * @param colWidth 列宽 默认 至少17个字节 
  272.      * @param out 输出流 
  273.      */  
  274.     public static void exportExcelX(Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {  
  275.         if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;  
  276.         // 声明一个工作薄  
  277.         SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存  
  278.         workbook.setCompressTempFiles(true);  
  279.           
  280.          //表头样式  
  281.         CellStyle titleStyle = workbook.createCellStyle();  
  282.         titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  283.         Font titleFont = workbook.createFont();  
  284.         titleFont.setFontHeightInPoints((short20);  
  285.         titleFont.setBoldweight((short700);  
  286.         titleStyle.setFont(titleFont);  
  287.           
  288.         // 列头样式  
  289.         CellStyle headerStyle = workbook.createCellStyle();  
  290.         headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  291.         headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  292.         headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  293.         headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  294.         headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  295.         headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  296.         Font headerFont = workbook.createFont();  
  297.         headerFont.setFontHeightInPoints((short12);  
  298.         headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  299.         headerStyle.setFont(headerFont);  
  300.           
  301.         // 单元格样式  
  302.         CellStyle cellStyle = workbook.createCellStyle();  
  303.         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  304.         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  305.         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  306.         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  307.         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  308.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  309.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  310.         Font cellFont = workbook.createFont();  
  311.         cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  312.         cellStyle.setFont(cellFont);  
  313.           
  314.         // 生成一个(带标题)表格  
  315.         SXSSFSheet sheet = workbook.createSheet();  
  316.         //设置列宽  
  317.         int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数  
  318.         int[] arrColWidth = new int[headMap.size()];  
  319.         // 产生表格标题行,以及设置列宽  
  320.         String[] properties = new String[headMap.size()];  
  321.         String[] headers = new String[headMap.size()];  
  322.         int ii = 0;  
  323.         for (Iterator<String> iter = headMap.keySet().iterator(); iter  
  324.                 .hasNext();) {  
  325.             String fieldName = iter.next();  
  326.   
  327.             properties[ii] = fieldName;  
  328.             headers[ii] = headMap.get(fieldName);  
  329.   
  330.             int bytes = fieldName.getBytes().length;  
  331.             arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;  
  332.             sheet.setColumnWidth(ii,arrColWidth[ii]*256);  
  333.             ii++;  
  334.         }  
  335.         // 遍历集合数据,产生数据行  
  336.         int rowIndex = 0;  
  337.         for (Object obj : jsonArray) {  
  338.             if(rowIndex == 65535 || rowIndex == 0){  
  339.                 if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示  
  340.   
  341.                 SXSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =0  
  342.                 for(int i=0;i<headers.length;i++)  
  343.                 {  
  344.                     headerRow.createCell(i).setCellValue(headers[i]);  
  345.                     headerRow.getCell(i).setCellStyle(headerStyle);  
  346.   
  347.                 }  
  348.                 rowIndex = 1;//数据内容从 rowIndex=1开始  
  349.             }  
  350.             JSONObject jo = (JSONObject) JSONObject.toJSON(obj);  
  351.             SXSSFRow dataRow = sheet.createRow(rowIndex);  
  352.             for (int i = 0; i < properties.length; i++)  
  353.             {  
  354.                 SXSSFCell newCell = dataRow.createCell(i);  
  355.   
  356.                 Object o =  jo.get(properties[i]);  
  357.                 String cellValue = "";   
  358.                 if(o==null) cellValue = "";  
  359.                 else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);  
  360.                 else if(o instanceof Float || o instanceof Double)   
  361.                     cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();  
  362.                 else cellValue = o.toString();  
  363.   
  364.                 newCell.setCellValue(cellValue);  
  365.                 newCell.setCellStyle(cellStyle);  
  366.             }  
  367.             rowIndex++;  
  368.         }  
  369.         // 自动调整宽度  
  370.         for (int i = 0; i < headers.length; i++) {  
  371.             sheet.autoSizeColumn(i);  
  372.         }  
  373.         try {  
  374.             workbook.write(out);  
  375.             workbook.close();  
  376.             workbook.dispose();  
  377.         } catch (IOException e) {  
  378.             e.printStackTrace();  
  379.         }  
  380.     }  
  381.       
  382.       
  383.       
  384.     //Web 导出excel  
  385.     public static void downloadExcelFile(String title,Map<String,String> headMap,JSONArray ja,HttpServletResponse response){  
  386.         try {  
  387.             ByteArrayOutputStream os = new ByteArrayOutputStream();  
  388.             ExcellUtil.exportExcelX(headMap,ja,null,0,os);  
  389.             byte[] content = os.toByteArray();  
  390.             InputStream is = new ByteArrayInputStream(content);  
  391.             // 设置response参数,可以打开下载页面  
  392.             response.reset();  
  393.   
  394.             response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");   
  395.             response.setHeader("Content-Disposition""attachment;filename="new String((title + ".xlsx").getBytes(), "iso-8859-1"));  
  396.             response.setContentLength(content.length);  
  397.             ServletOutputStream outputStream = response.getOutputStream();  
  398.             BufferedInputStream bis = new BufferedInputStream(is);  
  399.             BufferedOutputStream bos = new BufferedOutputStream(outputStream);  
  400.             byte[] buff = new byte[8192];  
  401.             int bytesRead;  
  402.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  403.                 bos.write(buff, 0, bytesRead);  
  404.   
  405.             }  
  406.             bis.close();  
  407.             bos.close();  
  408.             outputStream.flush();  
  409.             outputStream.close();  
  410.         }catch (Exception e) {  
  411.             e.printStackTrace();  
  412.         }  
  413.     }  
  414. }  

导出的实体类

http://pan.baidu.com/s/1c2EVh2w

[java]  view plain  copy
  1. package com.city.pms.entity.project.design.designDTO;  
  2.   
  3. import java.util.Date;  
  4. /** 
  5.  *  
  6.  * @Description: 导出的实体类 
  7.  * @CreateTime: 2017-11-20 上午9:47:56  
  8.  * @author: zhuhongfei  
  9.  * @version V1.0 
  10.  */  
  11. public class ProjectDesignDTO {  
  12.   
  13.     private String projectName;  
  14.     private String name;  
  15.     private String applicantUnit;  
  16.     private String reviewUnit;  
  17.     private String status;  
  18.     private String createName;  
  19.     private Date createDate;  
  20.       
  21.       
  22.     public String getProjectName() {  
  23.         return projectName;  
  24.     }  
  25.     public void setProjectName(String projectName) {  
  26.         this.projectName = projectName;  
  27.     }  
  28.     public String getName() {  
  29.         return name;  
  30.     }  
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34.     public String getApplicantUnit() {  
  35.         return applicantUnit;  
  36.     }  
  37.     public void setApplicantUnit(String applicantUnit) {  
  38.         this.applicantUnit = applicantUnit;  
  39.     }  
  40.     public String getReviewUnit() {  
  41.         return reviewUnit;  
  42.     }  
  43.     public void setReviewUnit(String reviewUnit) {  
  44.         this.reviewUnit = reviewUnit;  
  45.     }  
  46.     public String getStatus() {  
  47.         return status;  
  48.     }  
  49.     public void setStatus(String status) {  
  50.         this.status = status;  
  51.     }  
  52.       
  53.     public String getCreateName() {  
  54.         return createName;  
  55.     }  
  56.     public void setCreateName(String createName) {  
  57.         this.createName = createName;  
  58.     }  
  59.     public Date getCreateDate() {  
  60.         return createDate;  
  61.     }  
  62.     public void setCreateDate(Date createDate) {  
  63.         this.createDate = createDate;  
  64.     }  
  65.       
  66. }  

导入的实体类

http://pan.baidu.com/s/1i5pc6hf

[java]  view plain  copy
  1. package com.city.pms.entity.project.design.designA;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Date;  
  5.   
  6. /** 
  7.  *  
  8.  * @Description: 导入实体类 
  9.  * @CreateTime: 2017-11-16 上午9:23:21  
  10.  * @author: chenzw   
  11.  * @version V1.0 
  12.  */  
  13.   
  14. public class DesignA implements Serializable {  
  15.   
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 1749623906718021284L;  
  20.       
  21.     private Double id;  
  22.     private Integer eid;//整数  
  23.     private Integer safe;//安全值  
  24.     private Double prewarning;//预警值  
  25.     private Double alarm;//报警值  
  26.     private Double voerflow;//溢流值  
  27.     private Date createDate;//创建时间  
  28.       
  29.     public Double getId() {  
  30.         return id;  
  31.     }  
  32.     public void setId(Double id) {  
  33.         this.id = id;  
  34.     }  
  35.     public Integer getEid() {  
  36.         return eid;  
  37.     }  
  38.     public void setEid(Integer eid) {  
  39.         this.eid = eid;  
  40.     }  
  41.     public Integer getSafe() {  
  42.         return safe;  
  43.     }  
  44.     public void setSafe(Integer safe) {  
  45.         this.safe = safe;  
  46.     }  
  47.     public Double getPrewarning() {  
  48.         return prewarning;  
  49.     }  
  50.     public void setPrewarning(Double prewarning) {  
  51.         this.prewarning = prewarning;  
  52.     }  
  53.     public Double getAlarm() {  
  54.         return alarm;  
  55.     }  
  56.     public void setAlarm(Double alarm) {  
  57.         this.alarm = alarm;  
  58.     }  
  59.     public Double getVoerflow() {  
  60.         return voerflow;  
  61.     }  
  62.     public void setVoerflow(Double voerflow) {  
  63.         this.voerflow = voerflow;  
  64.     }  
  65.     public Date getCreateDate() {  
  66.         return createDate;  
  67.     }  
  68.     public void setCreateDate(Date createDate) {  
  69.         this.createDate = createDate;  
  70.     }  
  71.       
  72. }  

整体架构(dao,service,.xml,Controller)

http://pan.baidu.com/s/1hsF2Zha

[java]  view plain  copy
  1. //Dao层  
  2. //获取excel数据并插入数据库  
  3. public void insertDatasFromExcel(List<DesignA> designA);  
  4. //service层  
  5. //从excel导入到designA  
  6. public String insertDatasFromExcel(InputStream in,String fileName,Map<String, String> headMap);  
  7. //获取显示列表  
  8. public List<ProjectDesign> getAllProjectDesign();  
  9. //导出接口  
  10. public List<ProjectDesignDTO> getAllProjectDesignDTO();  

一、ServiceImpl-导入

[java]  view plain  copy
  1. package com.city.pms.service.project.design.designA;  
  2.   
  3. import java.io.InputStream;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.Iterator;  
  8. import java.util.LinkedHashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.commons.lang3.StringUtils;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.stereotype.Service;  
  15.   
  16. import com.city.pms.common.utils.ImportUtil2;  
  17. import com.city.pms.entity.project.design.designA.DesignA;  
  18. import com.city.pms.repository.project.design.designA.DesignADao;  
  19. @Service  
  20. public class DesignAServiceImpl implements DesignAService {  
  21.   
  22.     @Autowired    
  23.     private DesignADao designADao;  
  24.       
  25.     //  
  26.     @Override  
  27.     public DesignA save(String id) {  
  28.         // TODO Auto-generated method stub  
  29.         return designADao.save(id);  
  30.     }  
  31.     //导入  
  32.     @Override  
  33.     public String insertDatasFromExcel(InputStream in, String fileName,Map<String, String> headMap) {  
  34.         try {  
  35.             //首先调用工具类,读取excel文件,封装称实体集合  
  36.             List<List<Object>> listob = ImportUtil2.getListByExcel(in, fileName);  
  37.             //获取动态数组  动态的增加和减少元素  实现了ICollection和IList接口  灵活的设置数组的大小  
  38.             List<DesignA> designA = new ArrayList<DesignA>();   
  39.             //读取第一列,列头信息,第一行  
  40.             List<Object> list = listob.get(0);  
  41.             Iterator<String> keys = headMap.keySet().iterator();  
  42.             //LinkedHashMap保留插入的顺序(key,value)  
  43.             Map<String,Integer> newMap=new LinkedHashMap<String,Integer>();  
  44.             while(keys.hasNext()){  
  45.                 String key = keys.next();  
  46.                 String name = headMap.get(key);  
  47.                 boolean flag=true;  
  48.                 for (int i = 0; i < list.size(); i++) {  
  49.                     if(StringUtils.contains(name, list.get(i).toString())){  
  50.                         newMap.put(key,i);  
  51.                         flag=false;  
  52.                         break;  
  53.                     }  
  54.                 }  
  55.                 if(flag==true){  
  56.                     throw new Exception("Excel表格参数错误,缺少"+name);  
  57.                 }  
  58.             }  
  59.             //遍历listob数据,把数据放到List中  从第二行开始  
  60.             for (int i = 1; i < listob.size(); i++) {    
  61.                 List<Object> ob = listob.get(i);   
  62.                 DesignA design = new DesignA();    
  63.                 design.setEid(Integer.parseInt(ob.get(newMap.get("eid")).toString()));  
  64.                 design.setSafe(Integer.parseInt(ob.get(newMap.get("safe")).toString()));  
  65.                 //object类型转Double类型    
  66.                 design.setPrewarning(Double.parseDouble(ob.get(newMap.get("prewarning")).toString()));  
  67.                 design.setAlarm(Double.parseDouble(ob.get(newMap.get("alarm")).toString()));  
  68.                 design.setVoerflow(Double.parseDouble(ob.get(newMap.get("voerflow")).toString()));  
  69.                 Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(ob.get(newMap.get("createDate")).toString());  
  70.                 design.setCreateDate(parse);  
  71.                 //Add方法用于添加一个元素到当前列表的末尾  
  72.                 designA.add(design);  
  73.             }    
  74.             //批量插入  
  75.             designADao.insertDatasFromExcel(designA);  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.         return null;  
  80.     }  
  81.       
  82.   
  83. }  

ServiceImpl-导出

[java]  view plain  copy
  1. //导出  
  2.     @Override  
  3.     public List<ProjectDesignDTO> getAllProjectDesignDTO() {  
  4.         //获取动态数组  动态的增加和减少元素  实现了ICollection和IList接口  灵活的设置数组的大小  
  5.         List<ProjectDesignDTO> projectDesignList=new ArrayList<>();  
  6.         //获取列表  
  7.         List<ProjectDesign> allProjectDesign= projectDesignDao.getAllProjectDesign();  
  8.         //遍历projectDesign获取真值  
  9.          for (ProjectDesign projectDesign : allProjectDesign) {  
  10.              //需要导出的实体类  
  11.             ProjectDesignDTO projectDesignDTO=new ProjectDesignDTO();  
  12.             projectDesignDTO.setProjectName(projectDesign.getProjectinfoId().getName());  
  13.             projectDesignDTO.setName(projectDesign.getName());  
  14.             projectDesignDTO.setApplicantUnit(projectDesign.getApplicantUnit());  
  15.             projectDesignDTO.setReviewUnit(projectDesign.getReviewUnit());  
  16.             projectDesignDTO.setStatus(projectDesign.getStatus());  
  17.             projectDesignDTO.setCreateName(projectDesign.getCreator().getCnname());  
  18.             projectDesignDTO.setCreateDate(projectDesign.getCreateDate());  
  19.             //Add方法用于添加一个元素到当前列表的末尾  
  20.             projectDesignList.add(projectDesignDTO);  
  21.         }  
  22.          return projectDesignList;  
  23.     }  

一、导入-xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5. <mapper namespace="com.city.pms.repository.project.design.designA.DesignADao">  
  6.     <resultMap type="DesignA" id="DesignAMap">  
  7.         <id property="id" column="id"/>  
  8.         <id property="eid" column="eid"/>  
  9.         <id property="safe" column="safe"/>  
  10.         <id property="prewarning" column="prewarning"/>  
  11.         <id property="alarm" column="alarm"/>  
  12.         <id property="voerflow" column="voerflow"/>  
  13.         <id property="createDate" column="createDate"/>  
  14.     </resultMap>  
  15.       
  16.     <!-- 批量插入 -->  
  17.     <insert id="insertDatasFromExcel" parameterType="java.util.List">  
  18. <!--         <selectKey resultType ="java.lang.Integer" keyProperty"ID" order=   
  19.             "AFTER" > SELECT LAST_INSERT_ID() </selectKey > -->  
  20.         insert into WARNING   
  21.         (ID,EID,SAFE,PREWARNING,ALARM,OVERFLOW,CREATEDATE)  
  22.         SELECT WARNING_SEQUENCE.Nextval ID, A.*  
  23.         FROM(  
  24.         <foreach collection="list" item="item" index="index"  
  25.             separator="union all">  
  26.             SELECT  
  27.             #{item.eid},  
  28.             #{item.safe},  
  29.             #{item.prewarning},  
  30.             #{item.alarm},  
  31.             #{item.voerflow},  
  32.             #{item.createDate}  
  33.                 FROM  
  34.                 DUAL  
  35.         </foreach>  
  36.         ) A  
  37.     </insert>  
  38. </mapper>  

一、Controller

[java]  view plain  copy
  1. package com.city.pms.controller.project.design.designA;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.util.LinkedHashMap;  
  8. import java.util.Map;  
  9.   
  10. import javax.servlet.http.HttpServletRequest;  
  11.   
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.stereotype.Controller;  
  14. import org.springframework.ui.Model;  
  15. import org.springframework.web.bind.annotation.PathVariable;  
  16. import org.springframework.web.bind.annotation.RequestMapping;  
  17. import org.springframework.web.bind.annotation.RequestMethod;  
  18.   
  19. import com.city.pms.service.project.design.designA.DesignAService;  
  20.   
  21. /** 
  22.  *  
  23.  * @Description: TODO  
  24.  * @CreateTime: 2017-11-16 上午10:39:06  
  25.  * @author: zhuhongfei  
  26.  * @version V1.0 
  27.  */  
  28. @Controller  
  29. @RequestMapping("/designa")  
  30. public class DesignAController {  
  31.   
  32.     @Autowired  
  33.     private DesignAService designAService;  
  34.       
  35.     @RequestMapping(value= "toExcel",method = RequestMethod.GET)  
  36.     public String toExcel(){  
  37.         return "Excel";  
  38.     }  
  39.       
  40.     //导入  
  41.     @RequestMapping(value= "importExcel",method = RequestMethod.GET)  
  42.     public String importExcel(HttpServletRequest request, Model model){  
  43.           
  44.         try {  
  45.             File f=new File("E:\\嘉兴.xlsx");  
  46.             String fileName = "嘉兴.xlsx";  
  47.             Map<String, String> headMap=new LinkedHashMap<String, String>();  
  48.             headMap.put("eid""设备编号");  
  49.             headMap.put("safe""安全值");  
  50.             headMap.put("prewarning""预警值");  
  51.             headMap.put("alarm""报警值");  
  52.             headMap.put("voerflow""溢流值");  
  53.             headMap.put("createDate""创建时间");  
  54.             //数据导入  
  55.             InputStream in2=new FileInputStream(f);  
  56.             designAService.insertDatasFromExcel(in2, fileName, headMap);  
  57.             in2.close();  
  58.         } catch (IOException e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.         return "Excel";  
  62.     }  
  63.       
  64.     @RequestMapping(value = "/{id}/detail")  
  65.     public String detail(@PathVariable String id, Model model) {  
  66.         model.addAttribute("d",designAService.save(id));  
  67.         return "";  
  68.     }  
  69. }  
  70.       
  71.   
  72.   
  73. /** 
  74.      * 数据库数据导入excel(导出) 
  75.      *  
  76.      * @param response 
  77.      */  
  78.     @RequestMapping(value = "exportExcel",method = RequestMethod.GET)  
  79.     public void exportExcel(HttpServletResponse response){  
  80.             //读取数据库  
  81.             List<ProjectDesignDTO> allProjectDesign = projectDesignService.getAllProjectDesignDTO();  
  82.             //后台返回给前台时,可以把JSON对象转化成JSON字符串  
  83.             com.alibaba.fastjson.JSONArray ja= (com.alibaba.fastjson.JSONArray) com.alibaba.fastjson.JSONArray.toJSON(allProjectDesign);  
  84.             //LinkedHashMap保留插入的顺序(key,value)  
  85.             Map<String,String> headMap = new LinkedHashMap<String,String>();  
  86.             headMap.put("projectName","项目名称");  
  87.             headMap.put("name","方案名称");  
  88.             headMap.put("applicantUnit","申请单位");  
  89.             headMap.put("reviewUnit","评审单位");  
  90.             headMap.put("status","状态");  
  91.             headMap.put("createName","创建人");  
  92.             headMap.put("createDate","创建时间");  
  93.           String title = "工程设计方案 ";  
  94.          //调用工具类导出方法  
  95.          ExcellUtil.downloadExcelFile(title,headMap,ja,response);  
  96.     }  

一、Jsp

[javascript]  view plain  copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>  
  3. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  9. <html>  
  10. <head>  
  11. <base href="<%=basePath%>">  
  12.     <title>嘉兴市海绵城市规划建设运营平台</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <link href="css/css2.css" rel="stylesheet" type="text/css" />  
  20.     <script type="text/javascript"src="jquery/jquery-3.2.0.min.js"></script>  
  21. <style type="text/css">  
  22. body{text-align:center}  
  23. .ceshi1{margin:0 auto; width:750px;height:100px;}  
  24. </style>  
  25.   </head>  
  26.     
  27.   <body>  
  28.     <div class="warpper">  
  29.         <div class="top-warpper">  
  30.             <div class="logo-userInfo">  
  31.                 <h1 class="logo"><a href="#" >嘉兴市海绵城市规划建设运营平台</a></h1>  
  32.                 </div><br><br>  
  33.             <div class="ceshi1">  
  34.                 <button class="src-derive derive" id="derive">导出</button>  
  35.                     
  36.                 <!-- <tr>  
  37.                     <button class="src-derive leadin1" id="leadin" type="file" name="userUploadFile">导入</button>   
  38.                     <td><input type="file" name="userUploadFile"></td>  
  39.                 </tr> -->  
  40.                 <form action="/designa/importExcel.do" method="post" enctype="multipart/form-data" name="batchAdd" οnsubmit="return check();">  
  41.                     <div class="col-lg-4">  
  42.                         <input id="excel_file" type="file" name="filename" accept="xls/xlsx" size="50"/>  
  43.                     </div>  
  44.                     <input id="excel_button" class="src-derive leadin1" type="submit" value="导入Excel"/>  
  45.                    <%--  <font id="importMsg" color="red"><%=importMsg%></font><input type="hidden"/> --%>    
  46.                 </form>  
  47.             </div>  
  48.               
  49. <script type="text/javascript">  
  50.  var root="<%=basePath%>"  
  51. </script>  
  52. <script type="text/javascript"src="js/excel1.js"></script>  
  53. <script type="text/javascript"src="js/excel2.js"></script>  
  54.   
  55. </html>  

一、Js

[javascript]  view plain  copy
  1. //导出  
  2.         $(document).on("mousedown",".derive",function(){  
  3.             var id=$(this).attr("fileId");  
  4.             window.location.href=root+"/design/exportExcel.do";  
  5.         });  
  6.         //导入  
  7.         $(document).on("mousedown",".leadin1",function(){  
  8.             if(confirm("确定导入?")){  
  9.             var id=$(this).attr("fileId");  
  10.             window.location.href=root+"/designa/importExcel.do";  
  11.             }  
  12.         });  
SSM(Spring + SpringMVC + MyBatis)框架可以很方便地实现Excel文件的导入导出。下面是一个简单的实现流程: 1. 导出Excel文件 - 添加POI依赖,例如: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> ``` - 创建一个Excel文件,例如: ``` Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Hello, world!"); ``` - 将Excel文件写入输出流,例如: ``` response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=test.xls"); OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.flush(); outputStream.close(); ``` 2. 导入Excel文件 - 添加POI依赖,例如: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> ``` - 读取Excel文件,例如: ``` InputStream inputStream = new FileInputStream("test.xls"); Workbook workbook = new HSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); Cell cell = row.getCell(0); System.out.println(cell.getStringCellValue()); ``` - 将Excel数据保存到数据库,例如: ``` @Autowired private UserService userService; for (int i = 1; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); User user = new User(); user.setName(row.getCell(0).getStringCellValue()); user.setAge((int) row.getCell(1).getNumericCellValue()); userService.saveUser(user); } ``` 以上是一个简单的实现流程,具体实现方式可以根据实际需求进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值