1. 程式人生 > >poi實現excel上傳下載 親自實踐 教你十分鐘搞定

poi實現excel上傳下載 親自實踐 教你十分鐘搞定

今天要實現一個上傳excel的功能,之前寫過很多次,但是都沒有詳細整理過,今天整理下,方便以後直接拿來拷貝

首先從前臺來看,看了很多案例,基本兩種方法:一種是form表單提交,一種是非同步ajax方式。

在這裡我選擇ajax方式,因為我想要在前臺上傳完成後給使用者提示上傳成功還是失敗。

上jsp程式碼:

<div>  

<input id="upfile" type="file" name="upfile" onchange="fileUpload();"/>

<button class="btn btn-info btn-fill btn-wd" id="btn" name="btn">上傳excel</button>
<button class="btn btn-info btn-fill btn-wd" onclick="downloadTemp();">下載模板</button>

</div>

接下來js:

<script type="text/javascript">
function downloadTemp(){
window.location.href="/4sinfo/downloadTmpl.do";
}

function fileUpload(){
var fileName = $("#upfile").val();
if(fileName == null || fileName==""){
alert("請選擇檔案");
}else{
var fileType = fileName.substr(fileName.length-4,fileName.length);
if(fileType == ".xls" || fileType == "xlsx"){
var formData = new FormData();
formData.append("file",$("#upfile").prop("files")[0]);
$.ajax({
type:"post",
url:"/4sinfo/ajaxUpload.do",
data:formData,
cache:false,
processData:false,
contentType:false,
dataType:"json",
success:function(data){
if(null != data){
if(data.dataStatus == "1"){
if(confirm("上傳成功!")){
window.location.reload();
}
}else{
alert("上傳失敗!");
}
}
},
error:function(){
alert("上傳失敗!");
}
});
}else{
alert("上傳檔案型別錯誤!");
}
}
}

</script>

接下來是工具類(此處是借鑑別人的,整理了下,還算比較整齊通用,哈哈):

package com.antke.website.utils;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


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.springframework.web.multipart.MultipartFile;


import common.Logger;


public class POIUtils {

private static Logger logger = Logger.getLogger(POIUtils.class);
private final static String XLS = "xls";
private final static String XLSX = "xlsx";

public static List<String[]> readExcel(MultipartFile formFile) throws IOException{
//檢查檔案
checkFile(formFile);
//獲得工作簿物件
Workbook workbook = getWorkBook(formFile);
//建立返回物件,把每行中的值作為一個數組,所有的行作為一個集合返回
List<String[]> list = new ArrayList<>();
if(null!=workbook){
for(int sheetNum = 0;sheetNum<workbook.getNumberOfSheets();sheetNum++){
//獲取當前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(null == sheet){
continue;
}
//獲得當前sheet的開始行
int firstRowNum = sheet.getFirstRowNum();
//獲得當前sheet的結束行
int lastRowNum = sheet.getLastRowNum();
//迴圈除了第一行之外的所有行
for(int rowNum = firstRowNum+1;rowNum<=lastRowNum;rowNum++){
//獲得當前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//後的當前行的開始列
int firstCellNum = row.getFirstCellNum();
//獲得當前行的列數
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//迴圈當前行
for(int cellNum = firstCellNum;cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}

/**
* 獲取當前行資料
* @param cell
* @return
*/
@SuppressWarnings("deprecation")
private 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;
}


/**
* 獲得工作簿物件
* @param formFile
* @return
*/
public static Workbook getWorkBook(MultipartFile formFile){
//獲得檔名
//String fileName = formFile.getName();
String fileName = formFile.getOriginalFilename();
//建立Workbook工作簿物件,表示整個excel
Workbook workbook = null;
try {
//獲得excel檔案的io流
InputStream is = formFile.getInputStream();
//根據檔案字尾名不同(xls和xlsx)獲得不同的workbook實現類物件
if(fileName.endsWith(XLS)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(XLSX)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}

/**
*檢查檔案 
* @param formFile
* @throws IOException
*/
public static void checkFile(MultipartFile formFile) throws IOException{
//判斷檔案是否存在
if(null == formFile){
logger.error("檔案不存在!");
throw new FileNotFoundException("檔案不存在!");
}
//獲得檔名
//String fileName = formFile.getName();
String fileName = formFile.getOriginalFilename();
//判斷檔案是否是excel檔案
if(!fileName.endsWith(XLS) && !fileName.endsWith(XLSX)){
logger.error(fileName+"不是excel檔案!");
throw new IOException(fileName+"不是excel檔案!");
}
}



}

後臺action程式碼:

@RequestMapping("ajaxUpload.do")
    @ResponseBody
    public Map<String,Object> readExcel(@RequestParam(value = "file") MultipartFile excelFile,HttpServletRequest req,HttpServletResponse resp){
        Map<String, Object> param = new HashMap<String, Object>();
//        List<Car4SInfo> infoList = new ArrayList<Car4SInfo>();
        try {
List<String[]> rowList = POIUtils.readExcel(excelFile);
for(int i=0;i<rowList.size();i++){
String[] row = rowList.get(i);
Car4SInfo info = new Car4SInfo();
info.setDealers(row[0]);
info.setProvince(row[1]);
info.setCity(row[2]);
info.setAddress(row[3]);
info.setPhone(row[4]);
info.setCar_model(row[5]);
service.insertCar4SInfo(info);
}
} catch (IOException e) {
e.printStackTrace();
}
        param.put("dataStatus", 1);
return param;
    } 

 /**
     * 下載模板
     * @param request
     * @param response
     */
    @RequestMapping("downloadTmpl.do")
public void downloadTmpl(HttpServletRequest request,HttpServletResponse response){
    try {
    String fileName = "car4sinfo.xlsx";
    String path = request.getSession().getServletContext().getRealPath("/template/4sinfo")+"/"+fileName;
    path = path.replace("\\", "/");
   File file = new File(path);
   String filename = file.getName();
   // 取得檔案的字尾名。
       String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
       // 以流的形式下載檔案。
       InputStream fis = new BufferedInputStream(new FileInputStream(path));
       byte[] buffer = new byte[fis.available()];
       fis.read(buffer);
       fis.close();
       // 清空response
       response.reset();
       // 設定response的Header
       response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
       response.addHeader("Content-Length", "" + file.length());
       OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
       response.setContentType("application/octet-stream");
       toClient.write(buffer);
       toClient.flush();
       toClient.close();
    } catch (IOException ex) {
            ex.printStackTrace();
        }

}

搞定!!!!!