- 浏览: 54691 次
文章分类
- 全部博客 (46)
- java邮件组件 (1)
- java excel上传 (3)
- java 导出excel (1)
- java文件上传 (1)
- java文件上传、下载 (1)
- mytatis插件 (1)
- jquery.validate.min.js 非空验证 (1)
- 常用js工具 (2)
- 编程规范 (1)
- art.dialog页面 (1)
- java常量配置 (1)
- 框架知识 (2)
- web页面前段技术 (3)
- Method方法反射机制 (1)
- 数据库 (5)
- java解析excel数据 (1)
- java 反射 (1)
- spring 注解 (2)
- mybatis (4)
- Eclipse 模板 (1)
- web页面前端技术 (3)
- java 1.8 (1)
- 111111 (0)
- EL (1)
- mysql 分页 (1)
- excel导出 (1)
- 页面通用查询保存方法 (1)
- 自动创建数据库脚本 (1)
- 重复提交后台校验 (1)
- maven (1)
最新评论
/////////////////页面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("读取滚动计划异常!");
}
<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("读取滚动计划异常!");
}
相关推荐
上传本地文件到服务器进行解析,通过poi继续操作数据,易懂简单。
通过java解析上传文件,判断文件类型(excel或者csv),将解析后的数据映射到javabean,从而可以进一步操作,入库或者增添数据
java 解析Excel 并判断解析的数据类型__Eclipse工程,纯手工,无复制
回答csdn论坛:Java语言下excel导入到mysql数据库表...
java对Excel表格数据处理并以List集合返回(只要传Excel文件路径即可)
java版excel解析,并上传至mysql数据库。已包含jar包,数据库sql语句等,eclipse直接运行client.java
java上传并读取excel工具类 涉及到MultiFile转FIle 以及多个sheet页
java实现excel文件上传,并进行excel解析
本资源对应我的一片文章《基于Java语言SpringMVC框架的Excel上传解析以及下载教程》提供的jar依据,其中内容仅供参考,建议阅读那篇文章
通过工具类中读取绝对路径下的excel文档。 将文档放入到List集合。 将List集合转换成List集合。 生成随机数。 最后将结果放入到swing页面中进行效果显示。 模拟10个同学玩lol随机分组。 同学名字在excel中动态配置。
jxl JAVA Excel解析,主要用于修改、上传、下载Excel文件。
springboot整合easyexcel,上传解析Excel,下载导出Excel 运行环境 jdk8+tomcat9+IntelliJ IDEA+maven 项目技术(必填) springboot+easyexcel+html 数据库文件(可选) 无 依赖包文件(可选) maven管理jar包依赖...
前端js解析/读取excel文件,完整解析,简单操作,官网地址 http://oss.sheetjs.com/js-xlsx/
spring boot多文件上传、单文件上传、Excel解析源码 ...springboot 单文件上传、多文件上传、Excel文件上传解析、Excel文件下载; 运行环境 jdk8+tomcat9+IntelliJ IDEA+maven 项目技术(必填) springboot+poi+html
NULL 博文链接:https://little-bill.iteye.com/blog/1268491
NULL 博文链接:https://skycb.iteye.com/blog/2363483
/** * 根据 策划的配置表来生成 json * excel 目前使用的版本为2007,其他版本未测试, * excel 格式 定义 ... * 二进制的方式,一般用于 后台管理界面 的文件上传后的处理。 * @author wgq * */
此项目是基于springMVC实现的,基本流程为从前台jsp页面使用Ajax文件上传导入excel文件(.xls(97-03)/.xlsx(07以后)),传到后台controller调用相应工具类解析后返回指定参数做后续处理. 1. POIUtil.java工具类 解析...
使用struts和POI进行简单的Excel上传和解析,最后把Excel中的数据转化成类Person的实体,这是一个简单的案例,没有hibernate操作,相信只要知道怎么把Excel转换成实体并添加到List中,后面的都不是问题,本案例可以...
java上传文件,基于内存用poi读取excel内容. Excel内容解析完成后,可根据实际需求做相应处理