导入Excel表格持久化到数据库

页面按钮

 <form style="overflow:hidden;float:left" enctype="multipart/form-data"
                                          id="formSumbit" action="${ctx}order/uploadExcel.action" method="post"
                                          class="form-horizontal">
                                        <input id="upfile" type="file" name="upfile" value="选择文件" style="float:left"/>
                                        <input type="submit" id="submit1" value="导入物流信息" class="queryBtn"
                                               style="float:left"/>
                                    </form>

js

 var options = {
        beforeSubmit: function () {
            /*首先验证文件格式*/
            var fileName = $("#formSumbit").find("input[name=upfile]").val();
            if (fileName === '' || fileName == 'undefined') {
                alert('请选择文件');
                return false;
            }
            var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
            if (fileType !== 'xls' && fileType !== 'xlsx') {
                alert('文件格式不正确,excel文件!');
                return false;
            }
        },
        success: function (data) {
            if (data.success != true) {
                layerAlert(data.msg || '导入失败');
            } else {
                layerAlert(data.msg || '导入成功');
                deliveryProductTable.loadData();
            }
        }
    };
    $("#formSumbit").ajaxForm(options).submit(function () {
        return false;
    });

controller

@RequestMapping(value="uploadExcel")  
	@ResponseBody
    public JsonResult uploadExcel(HttpServletResponse response, HttpServletRequest request) throws Exception {  
        try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			System.out.println("通过传统方式form表单提交方式导入excel文件!");
			InputStream in = null;
			MultipartFile file = multipartRequest.getFile("upfile");
			if (file == null || file.isEmpty()) {
				return JsonResult.fail("文件不存在!");
				//throw new Exception("文件不存在!");
			}
			String name = file.getOriginalFilename();
			if(name.indexOf(".xls") < 0 && name.indexOf(".xlsx") < 0) {
				return JsonResult.fail("文件后缀格式不正确!");
			}

			in = file.getInputStream();
			List<List<String[]>> list = OrderExpressImportExcelUtil
					.getBankListByExcel(in, file.getOriginalFilename());
			//正确信息
			List<String[]> dataList = list.get(0);
			plOrderService.dealOrderExpressInfo(dataList);
			//错误信息
			List<String[]> errorList = list.get(1);
			if (errorList != null
					&& (errorList != null && errorList.size() > 0)) {
				ErrorExcel.donwloadExcel(response, request,
						"/templet/templeterror.xls", "错误信息表", errorList);
			}

			return JsonResult.succeed();
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.fail(e.getMessage());
		}
        
	}

maven

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
<spring.version>4.0.2.RELEASE</spring.version>

系统工具类

/*
 * Copyright 2002-2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.multipart;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

/**
 * Provides additional methods for dealing with multipart content within a
 * servlet request, allowing to access uploaded files.
 * Implementations also need to override the standard
 * {@link javax.servlet.ServletRequest} methods for parameter access, making
 * multipart parameters available.
 *
 * <p>A concrete implementation is
 * {@link org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest}.
 * As an intermediate step,
 * {@link org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest}
 * can be subclassed.
 *
 * @author Juergen Hoeller
 * @author Trevor D. Cook
 * @since 29.09.2003
 * @see MultipartResolver
 * @see MultipartFile
 * @see javax.servlet.http.HttpServletRequest#getParameter
 * @see javax.servlet.http.HttpServletRequest#getParameterNames
 * @see javax.servlet.http.HttpServletRequest#getParameterMap
 * @see org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
 * @see org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest
 */
public interface MultipartHttpServletRequest extends HttpServletRequest, MultipartRequest {

	/**
	 * Return this request's method as a convenient HttpMethod instance.
	 */
	HttpMethod getRequestMethod();

	/**
	 * Return this request's headers as a convenient HttpHeaders instance.
	 */
	HttpHeaders getRequestHeaders();

	/**
	 * Return the headers associated with the specified part of the multipart request.
	 * <p>If the underlying implementation supports access to headers, then all headers are returned.
	 * Otherwise, the returned headers will include a 'Content-Type' header at the very least.
	 */
	HttpHeaders getMultipartHeaders(String paramOrFileName);

}
/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.multipart;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * A representation of an uploaded file received in a multipart request.
 *
 * <p>The file contents are either stored in memory or temporarily on disk.
 * In either case, the user is responsible for copying file contents to a
 * session-level or persistent store as and if desired. The temporary storages
 * will be cleared at the end of request processing.
 *
 * @author Juergen Hoeller
 * @author Trevor D. Cook
 * @since 29.09.2003
 * @see org.springframework.web.multipart.MultipartHttpServletRequest
 * @see org.springframework.web.multipart.MultipartResolver
 */
public interface MultipartFile {

	/**
	 * Return the name of the parameter in the multipart form.
	 * @return the name of the parameter (never {@code null} or empty)
	 */
	String getName();

	/**
	 * Return the original filename in the client's filesystem.
	 * <p>This may contain path information depending on the browser used,
	 * but it typically will not with any other than Opera.
	 * @return the original filename, or the empty String if no file
	 * has been chosen in the multipart form, or {@code null}
	 * if not defined or not available
	 */
	String getOriginalFilename();

	/**
	 * Return the content type of the file.
	 * @return the content type, or {@code null} if not defined
	 * (or no file has been chosen in the multipart form)
	 */
	String getContentType();

	/**
	 * Return whether the uploaded file is empty, that is, either no file has
	 * been chosen in the multipart form or the chosen file has no content.
	 */
	boolean isEmpty();

	/**
	 * Return the size of the file in bytes.
	 * @return the size of the file, or 0 if empty
	 */
	long getSize();

	/**
	 * Return the contents of the file as an array of bytes.
	 * @return the contents of the file as bytes, or an empty byte array if empty
	 * @throws IOException in case of access errors (if the temporary store fails)
	 */
	byte[] getBytes() throws IOException;

	/**
	 * Return an InputStream to read the contents of the file from.
	 * The user is responsible for closing the stream.
	 * @return the contents of the file as stream, or an empty stream if empty
	 * @throws IOException in case of access errors (if the temporary store fails)
	 */
	InputStream getInputStream() throws IOException;

	/**
	 * Transfer the received file to the given destination file.
	 * <p>This may either move the file in the filesystem, copy the file in the
	 * filesystem, or save memory-held contents to the destination file.
	 * If the destination file already exists, it will be deleted first.
	 * <p>If the file has been moved in the filesystem, this operation cannot
	 * be invoked again. Therefore, call this method just once to be able to
	 * work with any storage mechanism.
	 * @param dest the destination file
	 * @throws IOException in case of reading or writing errors
	 * @throws IllegalStateException if the file has already been moved
	 * in the filesystem and is not available anymore for another transfer
	 */
	void transferTo(File dest) throws IOException, IllegalStateException;

}

应用工具类

package com.noah.ake.core.export;

import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

public class OrderExpressImportExcelUtil {
		
	private final static String excel2003L =".xls";    //2003- 版本的excel  
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
      
    /** 
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象 
     * @param in,fileName 
     * @return 
     * @throws IOException  
     */  
    public static List<List<String[]>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
        List<List<String[]>> list = Lists.newArrayList();
          
        //创建Excel工作薄  
        Workbook work = getWorkbook(in,fileName);
        if(null == work){  
            throw new Exception("创建Excel工作薄为空!");  
        }  
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
          
        sheet = work.getSheetAt(0);  
        
        //错误集合
        List<String[]> errorList= Lists.newArrayList();
        
        //遍历当前sheet中的所有行
        List<String[]> dataList = Lists.newArrayList();
        for (int j = 2; j < sheet.getLastRowNum()+1; j++) {  
            row = sheet.getRow(j);  
            if(row==null||row.getFirstCellNum()==j){continue;}  
            //遍历所有的列  
            String[] data=new String[11];
            boolean validFlag = true;
            for (int y = 0; y < 10; y++) {
                cell = row.getCell(y);  
                if(cell!=null){
                	data[y]=(String) getCellValue(cell);
                }
                else{
                	if(cell==null){
                    	String[] error={"在"+(j+1)+"行"+(y+1)+"列","数据没有填写"};
                        validFlag = false;
                    	errorList.add(error);
                    	break;
                    }

                }
            }
            if(validFlag) {
                dataList.add(data);
            }
        }
        //填入数据
        list.add(dataList);
        //填入错误信息
        list.add(errorList);
        in.close();
        return list;  
    }  
      
    /** 
     * 描述:根据文件后缀,自适应上传文件的版本  
     * @param inStr,fileName 
     * @return 
     * @throws Exception 
     */  
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));  
        if(excel2003L.equals(fileType)){  
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){  
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{  
            throw new Exception("解析的文件格式有误!");  
        }  
        return wb;  
    }  
  
    /** 
     * 描述:对表格中数值进行格式化 
     * @param cell 
     * @return 
     */  
    public static Object getCellValue(Cell cell){
        Object value = null;  
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符  
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化  
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字  
         
        switch (cell.getCellType()) {  
        case Cell.CELL_TYPE_STRING:
            value = cell.getRichStringCellValue().getString();  
            break;  
        case Cell.CELL_TYPE_NUMERIC:
            if("General".equals(cell.getCellStyle().getDataFormatString())){  
                value = df.format(cell.getNumericCellValue());
            }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){  
                value = sdf.format(cell.getDateCellValue());  
            }else{  
                value = df2.format(cell.getNumericCellValue());  
            }  
            break;  
        case Cell.CELL_TYPE_BOOLEAN:
            value = cell.getBooleanCellValue();  
            break;  
        case Cell.CELL_TYPE_BLANK:
            value = "";  
            break;  
        default:  
            break;  
        }  
        return value;  
    }

}
package com.cn.pinliang.plugin.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.cn.pinliang.common.pojo.OrderOnlineProduct;

public class ErrorExcel  {
	
	/** 
     * 描述:根据文件路径获取项目中的文件 
     * @param fileDir 文件路径 
     * @return 
     * @throws Exception 
     */  
    public static File getExcelFile(HttpServletRequest request,String fileDir) throws Exception{  
        File file = null;  
        String path =request.getServletContext().getRealPath("")  
        		+ fileDir;
        file = new File(path);  
        if(!file.exists()){  
            throw new Exception("模板文件不存在!");  
        }  
        return file;  
    }  

	public static Workbook writeNewExcel(File file,List<String[]> errorList) throws Exception{
		Workbook wb = null;  
        Row row = null;   
        Cell cell = null;  
          
        FileInputStream fis = new FileInputStream(file);  
        wb = new HSSFWorkbook(fis);    //获取工作薄  
        Sheet sheet = wb.getSheetAt(0);
        
        //获得表格的总列的数量
//        int columnNum=sheet.getRow(1).getPhysicalNumberOfCells();
        //获得表格的插入数据的行数
        int lastRow = sheet.getLastRowNum()+1;    
        
        //循环插入数据  
        CellStyle cs = setSimpleCellStyle(wb);    //Excel单元格样式  
        if(errorList==null||(errorList!=null&&errorList.size()==0)){
        	return wb;
        }
        for (int i = 0; i < errorList.size(); i++) {  
            row = sheet.createRow(lastRow+i); //创建新的ROW,用于数据插入  
              
            //按项目实际需求,在该处将对象数据插入到Excel中  
            String[] record  = errorList.get(i);  
            if(null==record){  
                break;  
            }  
            
          //Cell赋值开始  
          cell = row.createCell(0);  
          cell.setCellValue(record[0]);  
          cell.setCellStyle(cs);  
        
          cell = row.createCell(1);  
          cell.setCellValue(record[1]);  
          cell.setCellStyle(cs);  
              
        } 
        
        return wb;  
	}
	
	public static void donwloadExcel(HttpServletResponse response, HttpServletRequest request, String fileAddr,String fileName,List list){
		try{
			File file=getExcelFile(request,fileAddr);
			Workbook wb=writeNewExcel(file, list);
			OutputStream os = response.getOutputStream();// 取得输出流  
	        response.setContentType("application/vnd.ms-excel");  
	        response.setHeader("Content-disposition",  
	        "attachment;filename="+new String((fileName).getBytes(), "iso-8859-1")+".xls");  
	        wb.write(os);  
	        os.close();  
        } catch (Exception e) {  
	        e.printStackTrace();  
        }  
	}
	
	/** 
     * 描述:设置简单的Cell样式 
     * @return 
     */  
    public static CellStyle setSimpleCellStyle(Workbook wb){  
        CellStyle cs = wb.createCellStyle();  
          
        cs.setBorderBottom(CellStyle.BORDER_THIN); //下边框  
        cs.setBorderLeft(CellStyle.BORDER_THIN);//左边框  
        cs.setBorderTop(CellStyle.BORDER_THIN);//上边框  
        cs.setBorderRight(CellStyle.BORDER_THIN);//右边框  
        cs.setAlignment(CellStyle.ALIGN_CENTER); // 居中  
          
        return cs;  
    }
    
    
}


正确信息的处理,将datalist中的数据经过处理持久化到数据库

@Override
	@Transactional
	public void dealOrderExpressInfo(List<String[]> dataList) throws Exception {
		for(String[] data:dataList){
			//订单编号
			String orderNo=data[2];
			//快递公司
			String companyNO=Double.valueOf(data[0].trim()).intValue() + "";
//			String[] temp=company.split(" ");
//			String companyNO=temp[0];
			//物流号
			String expressNo=data[1];
			//查询订单是否存在
			PlOrder plOrder=plOrderMapper.selectByOrderId(orderNo);
			//1.存在
			if(plOrder!=null && plOrder.getReceiptState() == 0  && DataUtil.isNotEmpty(companyNO) && DataUtil.isNotEmpty(expressNo)){//必须是未发货的
				PlOrderExpress plOrderExpress=plOrderExpressMapper.selectByExpressId(expressNo);
				if(plOrderExpress!=null){
					plOrderExpress.setExpressCompany(companyNO);
					plOrderExpress.setExpressOrderId(expressNo);
					plOrderExpress.setDeliveryDate(new Date());
					plOrderExpressMapper.updateByPrimaryKeySelective(plOrderExpress);

					//改变订单发货状态
					plOrder.setReceiptState(1);
					plOrder.setReceiptDate(new Date());
					plOrderMapper.updateByPrimaryKeySelective(plOrder);
				}
				else{
					plOrderExpress=new PlOrderExpress();
					plOrderExpress.setPlOrderId(plOrder.getId());
					plOrderExpress.setExpressCompany(companyNO);
					plOrderExpress.setExpressOrderId(expressNo);
					plOrderExpress.setDeliveryDate(new Date());
					plOrderExpressMapper.insertSelective(plOrderExpress);
					
					//改变订单发货状态
					plOrder.setReceiptState(1);
					plOrder.setReceiptDate(new Date());
					plOrderMapper.updateByPrimaryKeySelective(plOrder);
				}
			}
		}
	}


猜你喜欢

转载自blog.csdn.net/a11121112111a/article/details/79973918