`

java 上传解析excel文件

阅读更多
/////////////////页面js代码
<script type="text/javascript">
var planMonth = "${param.planMonth}";
function import_rollPlan() {
var fileName = $("#excel").val();
if($("#excel").val()==''){
art.dialog({
content : "请选择文件",
lock : true
});
return;
}
if(fileName.lastIndexOf(".xlsx") != -1 || fileName.lastIndexOf(".xls") != -1) {
art.dialog({
width : "200px",
content:"文件加载成功,是否确定导入",
lock  : true,
button: [{name:'是',
         callback:function (){
window.setTimeout(function(){
$("#upForm").ajaxSubmit({
url : "${contextPath}/service/pageReq",
type : 'post',
    dataType : "json",
data : {content:"planMonth:" + planMonth, needcontrolprocess : "purRollPlanService.importRollPlan"},
success : function(data) {
var dialog  = art.dialog.get('importing_dialog');
dialog.close();
if (data.status == "FAIL") {
art.dialog({
title : "提示",
width : "350px",
content : "数据格式非法,导入失败!",
lock : true,
ok: function () {
_myDialog.close();
doSearch();
}
});
} else {
art.dialog({
title : "提示",
width : "350px",
content : data.expData.impResultMsg,
lock : true,
ok: function () {
_myDialog.close();
doSearch();
}
});
}
}
});
},10);
      
       art.dialog({
       id : "importing_dialog",
       title : "提示",
width : "200px",
content : "正在导入,请稍等...",
lock  : true
       });
      
},focus: true},
{name:'否'}
]
});
} else {
alert("请选择正确的excel文件!")
}

}
</script>

//////////////////
public abstract class AbstractExcelReader {

public abstract void doParse(Workbook workbook);
        /*
         *相当于
Reader(new a());

public class a implements Validate {

@Override
public void doValidate(InputStream inputStream) throws Exception {


String fileType = getType(inputStream);
if (StringUtils.isBlank(fileType)
|| (!FileType.XLSX.getValue().equals(fileType)
&& !FileType.XLS_DOC.getValue().equals(fileType) && !FileType.XLSX_DOCX
.getValue().equals(fileType))) {
throw new ServiceException("上传失败,请选择Excel类型文件! ");
}



}

}
        */
public void Reader() throws Exception {

Reader((InputStream inputStream) -> {

String fileType = getType(inputStream);
if (StringUtils.isBlank(fileType)
|| (!FileType.XLSX.getValue().equals(fileType)
&& !FileType.XLS_DOC.getValue().equals(fileType) && !FileType.XLSX_DOCX
.getValue().equals(fileType))) {
throw new ServiceException("上传失败,请选择Excel类型文件! ");
}

});
}

public void Reader(Validate validate) throws Exception {
MultiPartRequestWrapper mpRequest = (MultiPartRequestWrapper) HttpServletHolder
.getCurrentRequest();
//@sfit1092 解决ie安全警告
HttpServletHolder.getCurrentResponse().setContentType("application/octet-stream; charset=UTF-8");
// 导入的文件
File files = mpRequest.getFiles("excel")[0];
if (null == files) {
throw new FileNotFoundException("解析的文件不存在");
}
try (InputStream fileInputStream = new FileInputStream(files);) {
validate.doValidate(fileInputStream);

if (!fileInputStream.markSupported()) {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);) {
Workbook workbook = null;
if (POIFSFileSystem.hasPOIFSHeader(bufferedInputStream)) {
workbook = new HSSFWorkbook(bufferedInputStream);
} else if (POIXMLDocument
.hasOOXMLHeader(bufferedInputStream)) {
workbook = new XSSFWorkbook(
OPCPackage.open(bufferedInputStream));
} else {
throw new ServiceException("没有获得相应的workbook");
}
doParse(workbook);
}
}
}
}

/**
* * 判断文件类型
*
* @param inputStream
*
* @return 文件类型
*
*/
private static String getType(InputStream inputStream) throws IOException {
if (inputStream == null) {
return null;
}
String fileHead = getFileContent(inputStream);
if (fileHead == null || fileHead.length() == 0) {
return null;
}
fileHead = fileHead.toUpperCase();
FileType[] fileTypes = FileType.values();
for (FileType type : fileTypes) {
if (fileHead.startsWith(type.getValue())) {
return type.getValue();
}
}
throw new ServiceException("没有获取到响应的文件类型");
}

/**
* 得到文件头
*
* @param filePath
*            文件路径
* @return 文件头
* @throws IOException
*/
private static String getFileContent(InputStream inputStream)
throws IOException {
int length = 28;
byte[] b = null;
if (inputStream != null) {
inputStream.read(b = new byte[length], 0, length);
inputStream.skip(-length);
}
return FileTypeJudge.bytesToHexString(b);
}

public interface Validate {

public void doValidate(InputStream inputStream) throws Exception;
}

}


/***解析代码///////////////////////////
List<PurRollPlan> rollList = new ArrayList<PurRollPlan>();
try {
new AbstractExcelReader() {

@Override
public void doParse(Workbook workbook) {
Sheet f = workbook.getSheetAt(0);
int totalRow = f.getLastRowNum();
for (int i = 1; i <= totalRow; i++) {
Row row = f.getRow(i);
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
Cell cell3 = row.getCell(2);
Cell cell4 = row.getCell(3);
Cell cell5 = row.getCell(4);
// 计划月份转换
String planDate = cell1.getStringCellValue();
String planDate2 = planDate + "-01";
Date planDate3 = new Date();
try {
planDate3 = new SimpleDateFormat("yyyy-MM-dd")
.parse(planDate2);
} catch (ParseException e) {
logger.error("读取滚动计划时,设置计划月份异常!");
}
String materialCode = cell2.getStringCellValue();
String reqQuantity = cell3.getStringCellValue();
String reqDate = cell4.getStringCellValue();
reqDate = reqDate.replaceAll("\\/","-");
Date reqDate2 = new Date();
try {
reqDate2 = new SimpleDateFormat("yyyy-MM-dd")
.parse(reqDate);
} catch (ParseException e) {
logger.error("读取滚动计划时,设置需求日期异常!");
}
//加入计划月份和需求日期的校验
/*if(planDate3.after(reqDate2)) {


}*/
String supplierCode = cell5.getStringCellValue();
String supplierName = getSupplierName(supplierCode);
String materialName = getMaterialName(materialCode);
Date createTime = new Date();
String id = randomId();
ids.append(id);
PurRollPlan plan = new PurRollPlan();
plan.setId(id);
plan.setMaterialCode(materialCode);
plan.setMaturialDesc(materialName);
plan.setSupplierCode(supplierCode);
plan.setSupplierDesc(supplierName);
plan.setReqDate(reqDate2);
plan.setReqQuantity(Double.parseDouble(reqQuantity));
plan.setPlanDate(planDate3);
plan.setStatus("0");
plan.setSentStatus("0");
plan.setDelFlag("1");
String createPerson = UserUtil.getCurrentUser().getEmpCode();
plan.setCreatePerson(createPerson);
plan.setCreateTime(createTime);
rollList.add(plan);
}
}
}.Reader();
} catch (Exception e) {
logger.error("读取滚动计划异常!");
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics