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();
        }

}

搞定!!!!!

猜你喜欢

转载自blog.csdn.net/NB6063/article/details/80625672