匯入Excel表格持久化到資料庫
阿新 • • 發佈:2018-11-02
頁面按鈕
<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);
}
}
}
}