java spring execl,SpringMVC上传和解析Excel方法

示例:导入相关数据(Excel文件),相关的文件数据编辑好。

e78fef410a3e14e1e002ef1d2f613ff6.png

XML文件配置

再spring的xml文件中配置要上传文件的大小

Jsp界面配置

js文件

function upPolicy() {

document.sourcefile.action = "/login/policy/uploadCSV";

var submitUrl = document.getElementById("sourcefile").attributes["action"].value;

$.ajax({

type: "POST",

url: submitUrl,

data: $('#sourcefile').serialize(),

dataType: "json",

success: function (result) {

var json = JSON.parse(result);

if (json.flag == "0" || json.flag == "1") {

alert(tableJson.success);

return;

}

}

})

}

Controller配置

@RequestMapping(value = "/uploadCSV" ,method = RequestMethod.POST)

@ResponseBody

public String uploadCSV(@RequestParam("sourceFile") MultipartFile sourceFile, HttpServletRequest request,HttpServletResponse response) throws IOException{

//判断文件是否为空

if (sourceFile==null) return null;

//获取文件名

String name=sourceFile.getOriginalFilename();

//进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)

long size =sourceFile.getSize();

if (name==null ||("").equals(name) && size==0) return null;

//批量导入。参数:文件名,文件。

boolean b = batchImport(name,sourceFile);

JSONObject jsonObject=new JSONObject();

if(b){

jsonObject.put("flag",0);

jsonObject.put("success","批量导入EXCEL成功!");

}else{

jsonObject.put("flag",1);

jsonObject.put("success","批量导入EXCEL失败!");

}

return jsonObject.toString();

}

分层没有那么的详细,再Controller中做的处理

public boolean batchImport(String name,MultipartFile file){

boolean b = false;

//创建处理EXCEL

ExcelUtils readExcel=new ExcelUtils();

//解析excel,获取客户信息集合。

List cpolicyList = readExcel.getExcelInfo(name ,file);

if(cpolicyList != null){

b = true;

}

//迭代添加信息(注:实际上这里也可以直接将cpolicyList集合作为参数,

在Mybatis的相应映射文件中使用foreach标签进行批量添加。)

for(OTAPolicyModel customer:cpolicyList){

policyDao.insertOTAPolicy(customer);

}

return b;

}

工具类ExcelUtils.java

即上述方法中readExcel.getExcelInfo(name ,file);语句所调用的方法以及其他相关的方法

Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。不过这首先得判断Excel的版本而选择不同的Workbook的方式(2003版本对应的是HSSFWorkbook,2007版本及以上对应的是XSSFWorkbook)。此外,一般来说先将在客户端用户上传的文件拷贝一份至服务器的本地磁盘中,然后再从这个拷贝文件中进行读取,这样就避免了因客户端的网络异常或其他状况而在读取时造成的数据流失或损坏的情况。

package com.flight.inter.otaadapter.commons.util;

import com.flight.inter.otaadapter.model.OTAPolicyModel;

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 org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

import java.math.BigDecimal;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

/**

* Created by ling.zhang on 2016/12/29.

*/

public class ExcelUtils {

//总行数

private int totalRows = 0;

//总条数

private int totalCells = 0;

//错误信息接收器

private String errorMsg;

//构造方法

public ExcelUtils(){}

//获取总行数

public int getTotalRows() { return totalRows;}

//获取总列数

public int getTotalCells() { return totalCells;}

//获取错误信息

public String getErrorInfo() { return errorMsg; }

/**

* 验证EXCEL文件

* @param filePath

* @return

*/

public boolean validateExcel(String filePath){

if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){

errorMsg = "文件名不是excel格式";

return false;

}

return true;

}

/**

* 读EXCEL文件,获取客户信息集合

* @param

* @return

*/

public List getExcelInfo(String fileName, MultipartFile Mfile){

//把spring文件上传的MultipartFile转换成CommonsMultipartFile类型

CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //获取本地存储路径

File file = new File("D:\\fileupload");

//创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)

if (!file.exists()) file.mkdirs();

//新建一个文件

File file1 = new File("D:\\fileupload" + new Date().getTime() + ".xlsx");

//将上传的文件写入新建的文件中

try {

cf.getFileItem().write(file1);

} catch (Exception e) {

e.printStackTrace();

}

//初始化客户信息的集合

List customerList=new ArrayList();

//初始化输入流

InputStream is = null;

try{

//验证文件名是否合格

if(!validateExcel(fileName)){

return null;

}

//根据文件名判断文件是2003版本还是2007版本

boolean isExcel2003 = true;

if(WDWUtil.isExcel2007(fileName)){

isExcel2003 = false;

}

//根据新建的文件实例化输入流

is = new FileInputStream(file1);

//根据excel里面的内容读取客户信息

customerList = getExcelInfo(is, isExcel2003);

is.close();

}catch(Exception e){

e.printStackTrace();

} finally{

if(is !=null)

{

try{

is.close();

}catch(IOException e){

is = null;

e.printStackTrace();

}

}

}

return customerList;

}

/**

* 根据excel里面的内容读取客户信息

* @param is 输入流

* @param isExcel2003 excel是2003还是2007版本

* @return

* @throws IOException

*/

public List getExcelInfo(InputStream is,boolean isExcel2003){

List customerList=null;

try{

/** 根据版本选择创建Workbook的方式 */

Workbook wb = null;

//当excel是2003时

if(isExcel2003){

wb = new HSSFWorkbook(is);

}

else{//当excel是2007时

wb = new XSSFWorkbook(is);

}

//读取Excel里面客户的信息

customerList=readExcelValue(wb);

}

catch (IOException e) {

e.printStackTrace();

}

return customerList;

}

/**

* 读取Excel里面客户的信息

* @param wb

* @return

*/

private List readExcelValue(Workbook wb){

//得到第一个shell

Sheet sheet=wb.getSheetAt(0);

//得到Excel的行数

this.totalRows=sheet.getPhysicalNumberOfRows();

//得到Excel的列数(前提是有行数)

if(totalRows>=1 && sheet.getRow(0) != null){

this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();

}

List oTAPolicyModelList=new ArrayList();

OTAPolicyModel oTAPolicyModel;

//循环Excel行数,从第二行开始。标题不入库

for(int r=1;r

Row row = sheet.getRow(r);

if (row == null) continue;

oTAPolicyModel = new OTAPolicyModel();

try {

Thread.currentThread().sleep(1);

}catch (InterruptedException e){

e.printStackTrace();

}

oTAPolicyModel.setPolicyid(System.currentTimeMillis());

//循环Excel的列

for(int c = 0; c

Cell cell = row.getCell(c);

if (null != cell){

if(c==0){

oTAPolicyModel.setSource(cell.getStringCellValue());//供应商

}else if(c==1){

oTAPolicyModel.setVendee(cell.getStringCellValue());//输出渠道

}else if(c==2){

int triptype=0;

if (cell.getStringCellValue()=="全部"){

triptype=0;

}else if (cell.getStringCellValue().equals("单程")){

triptype=10;

}else if (cell.getStringCellValue().equals("往返")){

triptype=20;

}else if (cell.getStringCellValue().equals("单程直飞")){

triptype=11;

}else if (cell.getStringCellValue().equals("单程中转")){

triptype=12;

}else if (cell.getStringCellValue().equals("往返直飞")){

triptype=21;

}else if (cell.getStringCellValue().equals("往返中转")){

triptype=22;

}

oTAPolicyModel.setTriptype(triptype);//行程类型

}else if(c==3){

oTAPolicyModel.setCarrier(cell.getStringCellValue());//航司代码

}else if(c==4){

oTAPolicyModel.setDepcity(cell.getStringCellValue());//起飞城市

}else if(c==5){

oTAPolicyModel.setArrcity(cell.getStringCellValue());//降落城市

}else if(c==6){

oTAPolicyModel.setSalebegindatel(new BigDecimal(cell.getNumericCellValue()).setScale(0,BigDecimal.ROUND_HALF_DOWN).longValue());//销售开始日期

}else if(c==7){

oTAPolicyModel.setSaleenddatel(new BigDecimal(cell.getNumericCellValue()).setScale(0,BigDecimal.ROUND_HALF_DOWN).longValue());//销售结束日期

}else if(c==8){

oTAPolicyModel.setTravelbegindatel(new BigDecimal(cell.getNumericCellValue()).setScale(0,BigDecimal.ROUND_HALF_DOWN).longValue());//旅行开始日期

}else if(c==9){

oTAPolicyModel.setTravelenddatel(new BigDecimal(cell.getNumericCellValue()).setScale(0,BigDecimal.ROUND_HALF_DOWN).longValue());//旅行结束日期

}else if(c==10){

int cabintype=9;

if (cell.getStringCellValue().equals("全部")){

cabintype=9;

}else if (cell.getStringCellValue().equals("经济舱")){

cabintype=1;

}else if (cell.getStringCellValue().equals("商务")){

cabintype=2;

}else if (cell.getStringCellValue().equals("头等")){

cabintype=3;

}

oTAPolicyModel.setCabintype(cabintype);//舱位等级

}else if(c==11){

oTAPolicyModel.setFdtype(cell.getStringCellValue().equals("按价格区间")?1:2);//返点类型

}else if(c==12){

oTAPolicyModel.setCabin(cell.getStringCellValue());//舱位

}else if(c==13){

oTAPolicyModel.setPricebegin(cell.getNumericCellValue());//最低价格

}else if(c==14){

oTAPolicyModel.setPriceend(cell.getNumericCellValue());//最高价格

}else if(c==15){

oTAPolicyModel.setLmoney(cell.getNumericCellValue());//留钱

}else if(c==16){

oTAPolicyModel.setFpercent(cell.getNumericCellValue());//全价返点

}else if(c==17){

oTAPolicyModel.setFtpercent(cell.getNumericCellValue());//票面返点

}else if(c==18){

int carrierlimit=2;

if (cell.getStringCellValue().equals("是")){

carrierlimit=1;

}else if (cell.getStringCellValue().equals("否")){

carrierlimit=0;

}else if (cell.getStringCellValue().equals("无")){

carrierlimit=2;

}

oTAPolicyModel.setCarrierlimit(carrierlimit);//开票航司限制

}else if(c==19){

int transport=2;

if (cell.getStringCellValue().equals("是")){

transport=1;

}else if (cell.getStringCellValue().equals("否")){

transport=0;

}else if (cell.getStringCellValue().equals("无限制")){

transport=2;

}

oTAPolicyModel.setTransport(transport);//支持联运

}else if(c==20){

int sharedflight=2;

if (cell.getStringCellValue().equals("是")){

sharedflight=1;

}else if (cell.getStringCellValue().equals("否")){

sharedflight=0;

}else if (cell.getStringCellValue().equals("无")){

sharedflight=2;

}

oTAPolicyModel.setSharedflight(sharedflight);//支持共享航班

}else if(c==21){

oTAPolicyModel.setPstatus(cell.getStringCellValue().equals("有效")?1:2);//状态

}else if(c==22){

int faretype=0;

if (cell.getStringCellValue().equals("私有")){

faretype=1;

}else if (cell.getStringCellValue().equals("公布")){

faretype=2;

}else if (cell.getStringCellValue().equals("全部")){

faretype=0;

}

oTAPolicyModel.setFaretype(faretype);//运价类型

}else if(c==23){

oTAPolicyModel.setLimitprice(new BigDecimal(cell.getNumericCellValue()).setScale(0,BigDecimal.ROUND_HALF_DOWN).longValue());//加价限制

}else if(c==24){

int limittransit=2;

if (cell.getStringCellValue().equals("全部")){

limittransit=2;

}else if (cell.getStringCellValue().equals("适用")){

limittransit=0;

}else if (cell.getStringCellValue().equals("不适用")){

limittransit=1;

}

oTAPolicyModel.setLimittransit(limittransit);//中转限制

}else if(c==25){

oTAPolicyModel.setArrcity(cell.getStringCellValue());//中转城市

}else if(c==26){

int limitnation=2;

if (cell.getStringCellValue().equals("全部")){

limitnation=2;

}else if (cell.getStringCellValue().equals("适用")){

limitnation=0;

}else if (cell.getStringCellValue().equals("不适用")){

limitnation=1;

}

oTAPolicyModel.setLimitnation(limitnation);//国籍限制

}else if(c==27){

oTAPolicyModel.setArrcity(cell.getStringCellValue());//国籍

}else if (c==28){

oTAPolicyModel.setUsername(cell.getStringCellValue());//用户名

}

}

}

//添加客户

oTAPolicyModelList.add(oTAPolicyModel);

}

return oTAPolicyModelList;

}

}

工具类WDWUtil.java

package com.flight.inter.otaadapter.commons.util;

/**

* Created by ling.zhang on 2016/12/29.

*/

public class WDWUtil {

// @描述:是否是2003的excel,返回true是2003

public static boolean isExcel2003(String filePath) {

return filePath.matches(“^.+\.(?i)(xls)$”);

}

//@描述:是否是2007的excel,返回true是2007

public static boolean isExcel2007(String filePath) {

return filePath.matches("^.+\\.(?i)(xlsx)$");

}

}

说明:上面的代码为了阅读便利而先贴的是父方法,后贴的是子方法,而在实际的代码编辑中一般是先编辑子方法,后编辑父方法,如上面应该是先编辑工具类的代码,再编辑服务层的代码,最后编辑控制器的代码。

这样,整个流程就可以了,赶紧拿去测试吧

更多精彩内容,请点击 《spring上传下载专题》进行深入学习和研究。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
poi解析excel功能参数说明 此项目是基于springMVC实现的,基本流程为从前台jsp页面使用Ajax文件上传导入excel文件(.xls(97-03)/.xlsx(07以后)),传到后台controller调用相应工具类解析后返回指定参数做后续处理. 1. POIUtil.java工具类 解析通过MutilpartFile导入的Excel解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,通过workbook.getNumberOfSheets()获取工作簿数量,遍历工作簿,sheet.getLastRowNum()获取最大行数,将每行数据放入List list = new Array List(),并根据excel数据类型将器转换为字符串、数字、Boolean、公式、空值类型防止出现错误,最后返回一个list. 2. ExcelUtil.java工具类 解析通过MutilpartFile导入的Excel解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,采用Apache的POI的API来操作Excel,读取内容后保存到List中,再将List转Json(使用Linked,增删快,与Excel表顺序保持一致),Sheet表1————>List1<Map> 步骤1:根据Excel版本类型创建对于的Workbook以及CellSytle 步骤2:遍历每一个表中的每一行的每一列,这里做了些小改动,因为后续可能解析过后可能会保存入数据库,这里为第一行数据添加一个自定义表头 String[] p = new String[]{"name","age","sex","tel","address","e-mail","phone"}; 遍历的列数量以p的length为准 步骤3:一个sheet表就是一个Json,多表就多Json,对应一个 List 一个sheet表的一行数据就是一个 Map 一行中的一列,就把当前列头为key,列值为value存到该列的Map中 Map 一个线性Hash Map,以Excel的sheet表顺序,并以sheet表明作为key,sheet表转换Json后的字符串作为value 最后返回一个LinkedHashMap 3. ExcelToJsonPoi.java工具类 这个与上面工具类类似,不过这个是解析本地excel文件不是使用的流,使用迭代遍历sheet工作簿与每行每列的值,将所有类型作为String类型处理返回一个json对象输出至控制台
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值