ajax上傳檔案與excel表格匯入總結
阿新 • • 發佈:2019-01-06
一、excel匯入:(還有別的外掛像EasuPoi ,ExcelUtil等)
1、需要匯入包: Apache POI /
2、依賴: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>
官方Demo:
$(element).upload({ name: 'file',//上傳元件的name屬性,即<input type='file' name='file'/> action: '',//向伺服器請求的路徑 enctype: 'multipart/form-data',//mime型別,預設即可 params: {},//請求時額外傳遞的引數,預設為空 autoSubmit: true,//是否自動提交,即當選擇了檔案,自動關閉了選擇視窗後,是否自動提交請求。 onSubmit: function() {},//提交表單之前觸發事件 onComplete: function() {},//提交表單完成後觸發的事件 onSelect: function() {}//當用戶選擇了一個檔案後觸發事件 });
<style type="text/css"> .way2{ width: 50%; position: relative; background: #ededed; border-radius: 4px; height: 30px; line-height: 30px; } .way2 label{ display: block; width: 100%; height: 20px; text-align: center; } </style> <div class="way2"><label>檔案上傳<input id="inputFile" type="file" name="inputFile" style="width: 150px" onchange="uploadFile()" hidden/></label></div>
3、專案程式碼:
<script src="<%=path%>/webresource/js/ajaxfileupload.js"></script> <script> // 匯入Excell function uploadFile() { var file = $("#inputFile").val(); if (file != "" && file != null) { $.ajaxFileUpload({ url: "<%=path%>/ExcelImport/uploadExcel", secureuri: false, //name:'inputFile', fileElementId: 'inputFile',//file標籤的id dataType: 'json',//返回資料的型別 global:true, data:{headCode:'SumAmount'}, complete:function(){ $.messager.progress('close'); $("#inputFile").val(""); }, success: function (data) { if (data =="0") { HdUtil.messager.info("表格資料匯入成功"); // alert("上傳成功"); queryCodShipData(); } else { alert("上傳失敗"); } }, }); } } </script>
4、poi工具類:
package net.huadong.util;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class POIUtil {
private static Logger logger = LoggerFactory.getLogger(POIUtil.class);
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 讀入excel檔案,解析後返回
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException{
//檢查檔案
checkFile(file);
//獲得Workbook工作薄物件
Workbook workbook = getWorkBook(file);
//建立返回物件,把每行中的值作為一個數組,所有行作為一個集合返回
List<String[]> list =null;
if(workbook != null){
//遍歷Excel中所有的sheet
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//獲得當前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//獲得當前sheet的開始行
int firstRowNum = sheet.getFirstRowNum();
//獲得當前sheet的結束行
int lastRowNum = sheet.getLastRowNum();
//遍歷除了第一行的所有行
for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){
//獲得當前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//獲得當前行的開始列
int firstCellNum = row.getFirstCellNum();
//獲得當前行的列數
int lastCellNum = row.getPhysicalNumberOfCells();
System.out.println("當前列數:"+lastCellNum);
String[] cells = new String[row.getPhysicalNumberOfCells()];
//迴圈當前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list = new ArrayList<String[]>();
list.add(cells);
}
}
// workbook.close();
}
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
//判斷檔案是否存在
if(null == file){
logger.error("檔案不存在!");
throw new FileNotFoundException("檔案不存在!");
}
//獲得檔名
String fileName = file.getOriginalFilename();
//判斷檔案是否是excel檔案
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
logger.error(fileName + "不是excel檔案");
throw new IOException(fileName + "不是excel檔案");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//獲得檔名
String fileName = file.getOriginalFilename();
//建立Workbook工作薄物件,表示整個excel
Workbook workbook = null;
try {
//獲取excel檔案的io流
InputStream is = file.getInputStream();
//根據檔案字尾名不同(xls和xlsx)獲得不同的Workbook實現類物件
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007 及2007以上
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.info(e.getMessage());
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//把數字當成String來讀,避免出現1讀成1.0的情況
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判斷資料的型別
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //數字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字元";
break;
default:
cellValue = "未知型別";
break;
}
return cellValue;
}
}
5、後臺程式碼:(inputFile一點跟name屬性對應起來)Controller
//excel上傳
@RequestMapping( method = RequestMethod.POST ,value="/uploadExcel")
@ResponseBody
public String uploadExcel(@RequestParam(value="inputFile") MultipartFile inputFile) throws IOException {
String flag ="0";
try{
//這裡得到的是一個集合,裡面的每一個元素是String[]陣列
List<String[]> list = POIUtil.readExcel(inputFile);
codShipDataService.importExcelTable(list);
} catch(Exception e){
e.printStackTrace();
flag = "1";
}
return flag;
}
serviceImpl:
@Override
public void importExcelTable( List<String[]> list) throws Exception {
for(String[] strings:list ){
CodShipData codShipData= new CodShipData();
codShipData.setShipOfficeNum(strings[0]);
codShipData.setShortName(strings[1]);
codShipData.setcShipNam(strings[2]);
codShipData.seteShipNam(strings[3]);
codShipData.setNationality(strings[4]);
codShipData.setShipImo(strings[5]);
codShipData.setShipMmsi(strings[6]);
HdUtil.setCommonPro(true,codShipData);
BigDecimal bd = new BigDecimal(strings[8]);
codShipData.setShipGrossWgt(bd);
this.insertSelective(codShipData);
}
}
二、檔案上傳:
<script src="<%=path%>/webresource/js/ajaxfileupload.js"></script>
<script>
var file="";
function uploadFile() {
file = $("#inputFile").val();
if (file != "" && file != null) {
$.ajaxFileUpload({
url: "<%=path%>/Upload/ToUpload",
secureuri: false,
fileElementId: 'inputFile',//file標籤的id
dataType: 'json',//返回資料的型別
global: true,
data: {headCode: 'SumAmount',tableId:tableId,enterpriseName:enterpriseName,type:$("#codAttachment_attachmentType").val()},
contentType: 'application/json;charset=UTF-8',
complete: function () {
$.messager.progress('close');
$("#inputFile").val("");
},
success: function (data, status) //伺服器成功響應處理函式
{
if (data > 0) {
HdUtil.messager.info("表格資料匯入成功");
queryCodAttachment();
$('#codAttachmentDialog').dialog("close");
//
} else {
alert("上傳失敗");
}
}
}
)
}
}
</script>
<input id="inputFile" type="file" name="inputFile" style="width: 150px" onchange="uploadFile()"/>
後臺程式碼:
package net.huadong.controller;
import net.huadong.entity.CodAttachment;
import net.huadong.service.CodAttachmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Random;
@Controller
@RequestMapping(value = "/Upload")
public class UploadController {
@Resource
private CodAttachmentService codAttachmentService;
Logger logger = LoggerFactory.getLogger(UploadController.class);
@ResponseBody
@RequestMapping(method = RequestMethod.POST,value = "/ToUpload")
public Integer ToUploadFile(@RequestParam("inputFile") MultipartFile inputFile,HttpServletRequest request, HttpServletResponse response) {
CodAttachment codAttachment = new CodAttachment();
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setContentType("text/html;charset=utf-8");
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET,POST");
response.addHeader("Content-Type","multipart/form-data");
String originalFilename = null;
String ct =null;
String courseFile =null;
try {
if (inputFile.isEmpty()) {
return 0;
} else {
originalFilename = inputFile.getOriginalFilename();
// int i=originalFilename.lastIndexOf(".");
// name = originalFilename.substring(0,i-1);
long size = inputFile.getSize();
ct = inputFile.getContentType();
System.out.println("原始檔案全路徑名: " + originalFilename);
System.out.println("檔案大小:" + size + "KB");
System.out.println("檔案型別:" + ct);
System.out.println("========================================");
}
// 1. 獲取專案的全路徑
String root = request.getSession().getServletContext().getRealPath("/webapp/files");
String filename = inputFile.getOriginalFilename();
System.out.println("filename檔案:" + filename);
//獲取檔名,最後一個"\"後面的名字
int index = filename.lastIndexOf("\\");
if (index != -1) {
filename = filename.substring(index + 1);
}
//生成唯一的檔名
Random rnd = new Random();
String savename = rnd.nextInt() + "_" + filename;
System.out.println("savename檔案:" + savename);
//1. 根據檔名獲取hashcode
int hCode = filename.hashCode();
// 將hashcode轉化為無符號整數基數為16的整數引數的字串
String hex = Integer.toHexString(hCode);
//2. 根據字串生成檔案目錄
File dirFile = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
dirFile.mkdirs();
//4. 生成檔案
File destFile = new File(dirFile, savename);
courseFile = destFile.getCanonicalPath();
// 將檔案儲存到伺服器相應的目錄位置
String tableId = request.getParameter("tableId");
String enterpriseName = request.getParameter("enterpriseName");
String type = request.getParameter("type");
// System.out.println("fffgg=gggg"+saveEntity);
inputFile.transferTo(destFile);
codAttachment.setAttachmentName(originalFilename);
codAttachment.setAttachmentType(type);
codAttachment.setAttachmentUrl(courseFile);
codAttachment.setTableId(tableId);
codAttachment.setTableName(enterpriseName);
codAttachmentService.saveUpload(codAttachment);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
}
注意下格式