读取excel的两种式:1、POI 2、JXL

来源:互联网 发布:blu ray mac破解 编辑:程序博客网 时间:2024/05/17 21:55

第一种方式(通过POI,支持2003、2007、2010版EXCEL):

/**
* 简要说明:批量上传燃气管理信息
* 编写者:陈永丰
* 创建时间:2017年3月2日 下午5:21:02
* @param 说明
* @return 说明
*/
@RequestMapping(value="importTemplate")
@ResponseBody
public Result importTemplate(@RequestParam(value = "file", required = false) MultipartFile file,MultipartHttpServletRequest request){
Result result = new Result();
File saveDir = null;
Workbook workbook = null;
try {
if(!file.isEmpty()){
//临时目录 
String uploadPath = request.getSession().getServletContext().getRealPath("/upload/tempExcel");
saveDir = new File(uploadPath);
if(!saveDir.exists()){
saveDir.mkdirs();
       }
File destFile = new File(uploadPath,"test.xlsx");
//将界面选择的excel文件临时存储到临时目录里
file.transferTo(destFile);
FileInputStream is = new FileInputStream(destFile); // 文件流
workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的
int sheetCount = workbook.getNumberOfSheets()-1; // Sheet的数量
// 遍历每个Sheet
for (int i = 0; i < sheetCount; i++) {
Sheet sheet = workbook.getSheetAt(i);
this.gasManageService.saveBatchData(sheet, i);
}
result.setAck_code(Result.StatusCode_Success);
result.setMessage("批量上传成功!");
}
}catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
result.setAck_code(Result.StatusCode_Failure);
result.setMessage("批量上传失败!");
}finally{
try {
workbook.close();
if(saveDir!=null)saveDir.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

/**
* 简要说明:
* 编写者:陈永丰
* 创建时间:2017年3月6日 下午6:10:06
* @param 说明
* @return 说明
*/
@Transactional
public void saveBatchData(Sheet sheet,int sheetIndex){
int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
// 遍历每一行(从第下标为2的开始循环行,我是根据我读取数据的EXCEL结构决定的,你们也可以不用第下标为2的开始)
for (int r = 2; r < rowCount; r++) {
Row row = sheet.getRow(r);
GasManage entity = new GasManage();
entity.setGasId(IdUtils.uuid());
//所属街镇
Cell cell = row.getCell(1);
String jz = getCellContent(cell);
entity.setJz(String.valueOf(this.jzCk.convertJz(jz)));
//站点类别
Cell cell2 = row.getCell(2);
String siteType = getCellContent(cell2); 
entity.setSiteType(this.siteTypeCk.convert(siteType));
//单位名称 
Cell cell3 = row.getCell(3);
String gasName = getCellContent(cell3); 
entity.setGasName(gasName);
//地址
Cell cell4 = row.getCell(4);
String gasAddress = getCellContent(cell4); 
entity.setGasAddress(gasAddress);
//许可部门及有效期
Cell cell5 = row.getCell(5);
String deptAndDate = getCellContent(cell5);
if(StringUtils.isNotBlank(deptAndDate)){
deptAndDate = deptAndDate.trim();
//许可部门
String licenseDept = "";
if(deptAndDate.contains("(")){
licenseDept = deptAndDate.substring(0,deptAndDate.indexOf("("));
//许可有效期
String licenseDate = deptAndDate.substring(deptAndDate.indexOf("(")+1,deptAndDate.indexOf(")"));
entity.setLicenseDate(licenseDate);
}else{
licenseDept = deptAndDate;
}
entity.setLicenseDept(licenseDept);
}
//许可(备案)编号
Cell cell6 = row.getCell(6);
String licenseCode = getCellContent(cell6);
entity.setLicenseCode(licenseCode);
//负责人
Cell cell7 = row.getCell(7);
String gasPeople = getCellContent(cell7);
entity.setGasPeople(gasPeople);
//联系电话
Cell cell8 = row.getCell(8);
String gasTel = getCellContent(cell8);
entity.setGasTel(gasTel);
//标识牌编号
Cell cell9 = row.getCell(9);
String idCard = getCellContent(cell9);
entity.setIdCard(idCard);
//经纬度
Cell cell10 = row.getCell(10);
String jwd = getCellContent(cell10);
if(StringUtils.isNotBlank(jwd)){
String gasGpsX = jwd.substring(0,jwd.indexOf("23."));
entity.setGasGpsX(gasGpsX);
String gasGpsY = jwd.substring(jwd.indexOf("23."),jwd.length());
entity.setGasGpsY(gasGpsY);
}
//燃气类型
entity.setGasType("02");
//创建人编号
entity.setCreateUserId("10");
//最后修改人编号
entity.setLastUpdateUserId("10");
}
}

/**
* 简要说明:通过当前单元格格式获取单元格内容
* 编写者:陈永丰
* 创建时间:2017年3月6日 下午5:49:53
* @param 说明
* @return 说明
*/
private String getCellContent(Cell cell){
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
DecimalFormat df = new DecimalFormat("0");  
int cellType = cell.getCellType();
String cellValue = null;
switch (cellType) {
case Cell.CELL_TYPE_STRING: // 文本
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: // 数字、日期
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = fmt.format(cell.getDateCellValue()); // 日期型
} else {
cellValue = String.valueOf(df.format(cell.getNumericCellValue())); // 数字
}
break;
case Cell.CELL_TYPE_BLANK: // 空白
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // 错误
cellValue = "错误";
break;
default:
cellValue = "错误";
}
return cellValue;
}


第二种方式(通过JXL,提醒经测试JXL这个版本只支持2007版EXCEL以下):

/**

* 简要说明:批量上传燃气信息(读取EXCEL数据)
* 编写者:samphin
* 创建时间:2017年3月2日 下午5:21:02
* @param 说明
* @return 说明
*/
@RequestMapping(value="importTemplate")
@ResponseBody
public Result importTemplate(@RequestParam(value = "file", required = false) MultipartFile file,MultipartHttpServletRequest request){
Result result = new Result();
//new一个excel工作空间
Workbook rwb = null;
File excelFile = null;
try {
//这是获取服务端上传的EXCEL文件,然后取其内容
String dicPath = request.getSession().getServletContext().getRealPath("/upload/tempExcel");
excelFile = new File(dicPath+File.separator+File.separator+"test.xls");
if(!excelFile.exists()){
excelFile.mkdirs();
       }
file.transferTo(excelFile);
rwb = Workbook.getWorkbook(excelFile);
Sheet[] sheets = rwb.getSheets();
logger.info(sheets.length);
for (int j = 0;j<sheets.length;j++) {
Sheet sheet = sheets[j];
for(int i=2;i<sheet.getRows();i++){
//下面就是根据字段具体下标获取其文本内容,下面因为本人读取的字段是这些于是这样实现
//燃气基本信息对象
GasManage entity=new GasManage();
entity.setGasId(IdUtils.uuid());
//所在街镇
String jz = sheet.getCell(1,i).getContents();
entity.setJz(String.valueOf(jzCk.convertJz(jz)));
//燃气类型
entity.setGasType("02");
//站点类别
String siteType = sheet.getCell(2,i).getContents();
entity.setSiteType(siteTypeCk.convert(siteType));
//单位名称
String gasName = sheet.getCell(3,i).getContents();
entity.setGasName(gasName);
//地址
String gasAddress = sheet.getCell(4,i).getContents();
entity.setGasAddress(gasAddress);
//许可部门及有效期内容
String deptAndDate = sheet.getCell(5,i).getContents();
if(StringUtils.isNotBlank(deptAndDate)){
deptAndDate = deptAndDate.trim();
//许可部门
String licenseDept = "";
if(deptAndDate.contains("(")){
licenseDept = deptAndDate.substring(0,deptAndDate.indexOf("("));
//许可有效期
String licenseDate = deptAndDate.substring(deptAndDate.indexOf("(")+1,deptAndDate.indexOf(")"));
entity.setLicenseDate(licenseDate);
}else{
licenseDept = deptAndDate;
}
entity.setLicenseDept(licenseDept);
}
//许可(备案)编号
String licenseCode = sheet.getCell(6,i).getContents();
if(StringUtils.isNotBlank(licenseCode)){
licenseCode = licenseCode.trim();
entity.setLicenseCode(licenseCode.trim());
}
//负责人
String gasPeople = sheet.getCell(7,i).getContents();
entity.setGasPeople(gasPeople);
//负责人联系电话
String gasTel = sheet.getCell(8,i).getContents();
entity.setGasTel(gasTel);
//标识牌编号
String idCard = sheet.getCell(9,i).getContents();
entity.setIdCard(idCard);
//经纬度(截取经纬度分别设置到X,Y坐标里面)
String jwd = sheet.getCell(10,i).getContents();
if(StringUtils.isNotBlank(jwd)){
String gasGpsX = jwd.substring(0,jwd.indexOf("23."));
entity.setGasGpsX(gasGpsX);
String gasGpsY = jwd.substring(jwd.indexOf("23."),jwd.length());
entity.setGasGpsY(gasGpsY);
}
//创建人编号
entity.setCreateUserId("10");
//最后修改人编号
entity.setLastUpdateUserId("10");
}
}
}catch(BiffException e){
logger.error(e.getMessage(), e);
result.setAck_code(Result.StatusCode_Failure);
result.setMessage("批量上传失败!");
}catch (NumberFormatException e) {
logger.error(e.getMessage(), e);
result.setAck_code(Result.StatusCode_Failure);
result.setMessage("批量上传失败!");
}catch (NullPointerException e) {
e.printStackTrace();
result.setAck_code(Result.StatusCode_Failure);
result.setMessage("批量上传失败!");
logger.error(e.getMessage(), e);
}catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
result.setAck_code(Result.StatusCode_Failure);
result.setMessage("批量上传失败!");
}finally{
rwb.close();
if(excelFile!=null)excelFile.delete();
}
return result;

}


操作的实体类:

/**
 * 描述:燃气管理实体类
 * 编写者:陈永丰
 * 创建时间:2016年11月24日 下午2:47:59
 * 修改说明:
 */
public class GasManage extends BaseModel{


/**
* 燃气编号
*/
private String gasId;

/**
* 所属企业
*/
private String company;
    
    /**
     * 所属街镇
     */
    private String jz;
    
    /**
     * 站点类别  1:便民服务部 2:储罐站 3:供应站  4:汽车加气站 5:管道公司
     */
    private String siteType;
    
    /**
* 单位名称
*/
    private String gasName;
    
    /**
     * 燃气地址
     */
    private String gasAddress;
    
    /**
     * 许可部门
     */
    private String licenseDept;
    
    /**
     * 许可有效期
     */
    private String licenseDate;
    
    /**
     * 许可(备案)编号
     */
    private String licenseCode;
    
    /**
     * 标识牌编号
     */
    private String idCard;


    /**
     * 负责人
     */
    private String gasPeople;


    /**
     * 负责人联系电话
     */
    private String gasTel;


    /**
     * 燃气地图X坐标
     */
    private String gasGpsX;


    /**
     * 燃气地图Y坐标
     */
    private String gasGpsY;


    /**
     * 燃气备注
     */
    private String gasRemark;


    /**
     * 燃气管理类型 01:企业 02:管理机构
     */
    private String gasType;
    
    /**
     * 国土地图X坐标
     */
    private String arcgisX;
    /**
     * 国土地图Y坐标
     */
    private String arcgisY;
    
    public String getGasId() {
        return gasId;
    }


    public void setGasId(String gasId) {
        this.gasId = gasId == null ? null : gasId.trim();
    }


    public String getGasName() {
        return gasName;
    }


    public void setGasName(String gasName) {
        this.gasName = gasName == null ? null : gasName.trim();
    }


    public String getGasPeople() {
        return gasPeople;
    }


    public void setGasPeople(String gasPeople) {
        this.gasPeople = gasPeople == null ? null : gasPeople.trim();
    }


    public String getGasTel() {
        return gasTel;
    }


    public void setGasTel(String gasTel) {
        this.gasTel = gasTel == null ? null : gasTel.trim();
    }


    public String getGasAddress() {
        return gasAddress;
    }


    public void setGasAddress(String gasAddress) {
        this.gasAddress = gasAddress == null ? null : gasAddress.trim();
    }


    public String getGasGpsX() {
        return gasGpsX;
    }


    public void setGasGpsX(String gasGpsX) {
        this.gasGpsX = gasGpsX == null ? null : gasGpsX.trim();
    }


    public String getGasGpsY() {
        return gasGpsY;
    }


    public void setGasGpsY(String gasGpsY) {
        this.gasGpsY = gasGpsY == null ? null : gasGpsY.trim();
    }


    public String getGasRemark() {
        return gasRemark;
    }


    public void setGasRemark(String gasRemark) {
        this.gasRemark = gasRemark == null ? null : gasRemark.trim();
    }


    public String getGasType() {
        return gasType;
    }


    public void setGasType(String gasType) {
        this.gasType = gasType == null ? null : gasType.trim();
    }


public String getArcgisX() {
return arcgisX;
}


public void setArcgisX(String arcgisX) {
this.arcgisX = arcgisX;
}


public String getArcgisY() {
return arcgisY;
}


public void setArcgisY(String arcgisY) {
this.arcgisY = arcgisY;
}


public String getJz() {
return jz;
}


public void setJz(String jz) {
this.jz = jz;
}


public String getSiteType() {
return siteType;
}


public void setSiteType(String siteType) {
this.siteType = siteType;
}


public String getLicenseDept() {
return licenseDept;
}


public void setLicenseDept(String licenseDept) {
this.licenseDept = licenseDept;
}


public String getLicenseDate() {
return licenseDate;
}


public void setLicenseDate(String licenseDate) {
this.licenseDate = licenseDate;
}


public String getLicenseCode() {
return licenseCode;
}


public void setLicenseCode(String licenseCode) {
this.licenseCode = licenseCode;
}


public String getIdCard() {
return idCard;
}


public void setIdCard(String idCard) {
this.idCard = idCard;
}


public String getCompany() {
return company;
}


public void setCompany(String company) {
this.company = company;
}
}

0 0