spring mvc 4.3.2 + mybatis 3.4.1 + mysql 5.7.14 +shiro 幼兒園收費系統 之 從Excel導入數據功能

實現思路java

1. 上傳excel 文件到 服務器, excel 格式 apache

    第一行: 對象屬性,例如, id, title, msg, createTime 等,json

    二行及之後: 數據數組

    以下:服務器

 

2  而後用org.apache.poi 讀取excel 內容到 ArrayList<ArrayList<object>>中, 使用的工具類 是直接從網上找的。ExcelUtil1.javaapp

3 而後用FastJson 將ArrayList<ArrayList<object>> 轉換成 java POJO, xss

4 剩下的事情就是將 POJO 傳送給 service-->dao-->db 了。工具

 

    @RequestMapping(value = "/import")
    @ResponseBody
    public Map importFromExcel(@RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "type", required = false) Integer type,
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap model) {

        WebUtil.setHeader(response);
        
        Map<String,Object> map = new HashMap<String,Object>();
        
        String path = request.getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        //String fileName = new Date().getTime()+".png";
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        // 保存
        try {
            file.transferTo(targetFile);
        //讀取excel ArrayList
<ArrayList<Object>> list = ExcelUtil1.readExcel(targetFile); int i = 0; ArrayList<Object> cols = new ArrayList<Object>(); HashMap<String,Object> row = new HashMap<String,Object>(); for (ArrayList<Object> data :list){ if (i == 0){ for(Object o:data){ cols.add(o); } } else{ row.clear(); for(int j=0;j<data.size() && j <cols.size();j++){ row.put((String)cols.get(j), data.get(j)); } String json = JSON.toJSONString(row); logger.info("import json---it is:"+json);
            //轉換成對象 Msg msg
= JSON.toJavaObject(JSON.parseObject(json), Msg.class);
            //寫入到db
if (msg.getId() == null){ msgService.insert(msg); }else{ msgService.update(msg); } } i++; } targetFile.delete(); } catch (Exception e) { map.put("result", "failed"); map.put("error", e.getMessage()); e.printStackTrace(); return map; } map.put("result", "ok"); return map; }

5 ExcelUtil.java 的內容(謝謝分享的同窗)ui

 

  1 import java.io.ByteArrayOutputStream;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.OutputStream;
  7 import java.text.DecimalFormat;
  8 import java.text.SimpleDateFormat;
  9 import java.util.ArrayList;
 10 
 11 import org.apache.poi.hssf.usermodel.HSSFCell;
 12 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
 13 import org.apache.poi.hssf.usermodel.HSSFRow;
 14 import org.apache.poi.hssf.usermodel.HSSFSheet;
 15 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 16 import org.apache.poi.xssf.usermodel.XSSFCell;
 17 import org.apache.poi.xssf.usermodel.XSSFRow;
 18 import org.apache.poi.xssf.usermodel.XSSFSheet;
 19 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 20 
 21 public class ExcelUtil1 {
 22     //默認單元格內容爲數字時格式
 23     private static DecimalFormat df = new DecimalFormat("0");
 24     // 默認單元格格式化日期字符串 
 25     private static SimpleDateFormat sdf = new SimpleDateFormat(  "yyyy-MM-dd HH:mm:ss"); 
 26     // 格式化數字
 27     private static DecimalFormat nf = new DecimalFormat("0.00");  
 28     public static ArrayList<ArrayList<Object>> readExcel(File file){
 29         if(file == null){
 30             return null;
 31         }
 32         if(file.getName().endsWith("xlsx")){
 33             //處理ecxel2007
 34             return readExcel2007(file);
 35         }else{
 36             //處理ecxel2003
 37             return readExcel2003(file);
 38         }
 39     }
 40     /*
 41      * @return 將返回結果存儲在ArrayList內,存儲結構與二位數組相似
 42      * lists.get(0).get(0)表示過去Excel中0行0列單元格
 43      */
 44     public static ArrayList<ArrayList<Object>> readExcel2003(File file){
 45         try{
 46             ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
 47             ArrayList<Object> colList;
 48             HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
 49             HSSFSheet sheet = wb.getSheetAt(0);
 50             HSSFRow row;
 51             HSSFCell cell;
 52             Object value;
 53             for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
 54                 row = sheet.getRow(i);
 55                 colList = new ArrayList<Object>();
 56                 if(row == null){
 57                     //當讀取行爲空時
 58                     if(i != sheet.getPhysicalNumberOfRows()){//判斷是不是最後一行
 59                         rowList.add(colList);
 60                     }
 61                     continue;
 62                 }else{
 63                     rowCount++;
 64                 }
 65                 for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
 66                     cell = row.getCell(j);
 67                     if(cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
 68                         //當該單元格爲空
 69                         if(j != row.getLastCellNum()){//判斷是不是該行中最後一個單元格
 70                             colList.add("");
 71                         }
 72                         continue;
 73                     }
 74                     switch(cell.getCellType()){
 75                      case XSSFCell.CELL_TYPE_STRING:  
 76                             System.out.println(i + "行" + j + " 列 is String type");  
 77                             value = cell.getStringCellValue();  
 78                             break;  
 79                         case XSSFCell.CELL_TYPE_NUMERIC:  
 80                             if ("@".equals(cell.getCellStyle().getDataFormatString())) {  
 81                                 value = df.format(cell.getNumericCellValue());  
 82                             } else if ("General".equals(cell.getCellStyle()  
 83                                     .getDataFormatString())) {  
 84                                 value = nf.format(cell.getNumericCellValue());  
 85                             } else {  
 86                                 value = sdf.format(HSSFDateUtil.getJavaDate(cell  
 87                                         .getNumericCellValue()));  
 88                             }  
 89                             System.out.println(i + "行" + j  
 90                                     + " 列 is Number type ; DateFormt:"  
 91                                     + value.toString()); 
 92                             break;  
 93                         case XSSFCell.CELL_TYPE_BOOLEAN:  
 94                             System.out.println(i + "行" + j + " 列 is Boolean type");  
 95                             value = Boolean.valueOf(cell.getBooleanCellValue());
 96                             break;  
 97                         case XSSFCell.CELL_TYPE_BLANK:  
 98                             System.out.println(i + "行" + j + " 列 is Blank type");  
 99                             value = "";  
100                             break;  
101                         default:  
102                             System.out.println(i + "行" + j + " 列 is default type");  
103                             value = cell.toString();  
104                     }// end switch
105                     colList.add(value);
106                 }//end for j
107                 rowList.add(colList);
108             }//end for i
109             
110             return rowList;
111         }catch(Exception e){
112             return null;
113         }
114     }
115     
116     public static ArrayList<ArrayList<Object>> readExcel2007(File file){
117         try{
118             ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
119             ArrayList<Object> colList;
120             XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));
121             XSSFSheet sheet = wb.getSheetAt(0);
122             XSSFRow row;
123             XSSFCell cell;
124             Object value;
125             for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
126                 row = sheet.getRow(i);
127                 colList = new ArrayList<Object>();
128                 if(row == null){
129                     //當讀取行爲空時
130                     if(i != sheet.getPhysicalNumberOfRows()){//判斷是不是最後一行
131                         rowList.add(colList);
132                     }
133                     continue;
134                 }else{
135                     rowCount++;
136                 }
137                 for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
138                     cell = row.getCell(j);
139                     if(cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
140                         //當該單元格爲空
141                         if(j != row.getLastCellNum()){//判斷是不是該行中最後一個單元格
142                             colList.add("");
143                         }
144                         continue;
145                     }
146                     switch(cell.getCellType()){
147                      case XSSFCell.CELL_TYPE_STRING:  
148                             System.out.println(i + "行" + j + " 列 is String type");  
149                             value = cell.getStringCellValue();  
150                             break;  
151                         case XSSFCell.CELL_TYPE_NUMERIC:  
152                             if ("@".equals(cell.getCellStyle().getDataFormatString())) {  
153                                 value = df.format(cell.getNumericCellValue());  
154                             } else if ("General".equals(cell.getCellStyle()  
155                                     .getDataFormatString())) {  
156                                 value = nf.format(cell.getNumericCellValue());  
157                             } else {  
158                                 value = sdf.format(HSSFDateUtil.getJavaDate(cell  
159                                         .getNumericCellValue()));  
160                             }  
161                             System.out.println(i + "行" + j  
162                                     + " 列 is Number type ; DateFormt:"  
163                                     + value.toString()); 
164                             break;  
165                         case XSSFCell.CELL_TYPE_BOOLEAN:  
166                             System.out.println(i + "行" + j + " 列 is Boolean type");  
167                             value = Boolean.valueOf(cell.getBooleanCellValue());
168                             break;  
169                         case XSSFCell.CELL_TYPE_BLANK:  
170                             System.out.println(i + "行" + j + " 列 is Blank type");  
171                             value = "";  
172                             break;  
173                         default:  
174                             System.out.println(i + "行" + j + " 列 is default type");  
175                             value = cell.toString();  
176                     }// end switch
177                     colList.add(value);
178                 }//end for j
179                 rowList.add(colList);
180             }//end for i
181             
182             return rowList;
183         }catch(Exception e){
184             System.out.println("exception");
185             return null;
186         }
187     }
188     
189     public static void writeExcel(ArrayList<ArrayList<Object>> result,String path){
190         if(result == null){
191             return;
192         }
193         HSSFWorkbook wb = new HSSFWorkbook();
194         HSSFSheet sheet = wb.createSheet("sheet1");
195         for(int i = 0 ;i < result.size() ; i++){
196              HSSFRow row = sheet.createRow(i);
197             if(result.get(i) != null){
198                 for(int j = 0; j < result.get(i).size() ; j ++){
199                     HSSFCell cell = row.createCell(j);
200                     cell.setCellValue(result.get(i).get(j).toString());
201                 }
202             }
203         }
204         ByteArrayOutputStream os = new ByteArrayOutputStream();
205         try
206         {
207             wb.write(os);
208         } catch (IOException e){
209             e.printStackTrace();
210         }
211         byte[] content = os.toByteArray();
212         File file = new File(path);//Excel文件生成後存儲的位置。
213         OutputStream fos  = null;
214         try
215         {
216             fos = new FileOutputStream(file);
217             fos.write(content);
218             os.close();
219             fos.close();
220         }catch (Exception e){
221             e.printStackTrace();
222         }           
223     }
224     
225     public static DecimalFormat getDf() {
226         return df;
227     }
228     public static void setDf(DecimalFormat df) {
229         ExcelUtil1.df = df;
230     }
231     public static SimpleDateFormat getSdf() {
232         return sdf;
233     }
234     public static void setSdf(SimpleDateFormat sdf) {
235         ExcelUtil1.sdf = sdf;
236     }
237     public static DecimalFormat getNf() {
238         return nf;
239     }
240     public static void setNf(DecimalFormat nf) {
241         ExcelUtil1.nf = nf;
242     }
243     
244     public static void main(String[] args){
245         System.out.println("oo");
246         File file = new File("c:\\test\\a1.xlsx");
247         ArrayList<ArrayList<Object>> list = ExcelUtil1.readExcel(file);
248         for(ArrayList<Object> o :list){
249             for (Object b :o){
250                 System.out.println(b);
251             }
252         }
253     }
254 }

界面:spa

相關文章
相關標籤/搜索