1.html页面:
<formid="myform"method="post"enctype="multipart/form-data">
<table>
<tr>
<td></td>
<td>
<inputtype="file"name="filepath"id="filepath"
class="easyui-validatebox"required=true
validType="equalLength[4]"missingMessage="文件!"value=""/>
</td>
</tr>
<tralign="center">
<tdcolspan="2">
<aid="btn1"class="easyui-linkbutton"
data-options="iconCls:'icon-ok'"style="width:60px"
onclick="subForm();">OK</a>
<aid="btn2"class="easyui-linkbutton"
data-options="iconCls:'icon-cancel'"style="width:60px"
onclick="closeDig();">Cancel</a>
</td>
</tr>
</table>
</form>
<scripttype="text/javascript">
functionsubForm(){
if($('#myform').form('validate')){
/**
varfilepath=$("#filepath").val();
alert(filepath);
$.ajax({
url:'excleImport',
typs:"post",
data:{"filepath":filepath},
async:false,
error:function(request){
$('#dg').datagrid('reload');
closeDig();
$.messager.alert("操作提示","操作成功!","info");
},
success:function(data){
alert("success");
}
});
**/
varfilepath=$("#filepath").val();
varre=/(\\+)/g;
varfilename=filepath.replace(re,"#");
//对路径字符串进行剪切截取
varone=filename.split("#");
//获取数组中最后一个,即文件名
vartwo=one[one.length-1];
//再对文件名进行截取,以取得后缀名
varthree=two.split(".");
//获取截取的最后一个字符串,即为后缀名
varlast=three[three.length-1];
//添加需要判断的后缀名类型
vartp="xls,xlsx";
//返回符合条件的后缀名在字符串中的位置
varrs=tp.indexOf(last);
if(rs!=-1){
$("#myform").attr("action","excleImport");
$("#myform").submit();
}else{
$.messager.alert("操作提示","您选择的上传文件不是有效xls或者xlsx文件!","error");
returnfalse;
}
}else{
$.messager.alert("操作提示","请选择上传文件!","error");
}
}
</script>
2.java代码:
@RequestMapping("/excleImport")
publicvoidexcleImport(HttpServletRequestrequest)throwsIOException,Exception{
request.setCharacterEncoding("utf-8");//设置编码
//获得磁盘文件条目工厂
DiskFileItemFactoryfactory=newDiskFileItemFactory();
//获取文件需要上传到的路径
Stringpath=request.getRealPath("/upload/kaku");
FileuploadDir=newFile(path);
if(!uploadDir.exists()){
uploadDir.mkdirs();
}
factory.setRepository(uploadDir);
//设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室
factory.setSizeThreshold(1024*1024);
//高水平的API文件上传处理
ServletFileUploadupload=newServletFileUpload(factory);
//可以上传多个文件
List<FileItem>list=(List<FileItem>)upload.parseRequest(request);
for(FileItemitem:list)
{
//获取表单的属性名字
Stringname=item.getFieldName();
//如果获取的表单信息是普通的文本信息
if(item.isFormField())
{
//获取用户具体输入的字符串,名字起得挺好,因为表单提交过来的是字符串类型的
Stringvalue=item.getString();
request.setAttribute(name,value);
}
//对传入的非简单的字符串进行处理,比如说二进制的图片,电影这些
else
{
/**
*以下三步,主要获取上传文件的名字
*/
//获取路径名
Stringvalue=item.getName();
//索引到最后一个反斜杠
intstart=value.lastIndexOf("\\");
//截取上传文件的字符串名字,加1是去掉反斜杠,
Stringfilename=value.substring(start+1);
//文件后缀名
Stringprefix=filename.substring(filename.lastIndexOf(".")+1);
CardCentercardCenter=newCardCenter();
request.setAttribute(name,filename);
//真正写到磁盘上
//它抛出的异常用exception捕捉
//item.write(newFile(path,filename));//第三方提供的
//手动写的
//OutputStreamout=newFileOutputStream(newFile(path,filename));
InputStreamin=item.getInputStream();
List<CardCenter>listFromExcel=(List<CardCenter>)ExelUtil.exportListFromExcel(in,prefix,cardCenter);
this.cardCenterService.excleImport(listFromExcel);
/*intlength=0;
byte[]buf=newbyte[1024];
System.out.println("获取上传文件的总共的容量:"+item.getSize());
//in.read(buf)每次读到的数据存放在buf数组中
while((length=in.read(buf))!=-1)
{
//在buf数组中取出数据写到(输出流)磁盘上
out.write(buf,0,length);
}*/
in.close();
//out.close();
}
}
}
3.java代码:
publicclassExelUtil{
//第一列开始
privatestaticintstart=0;
//最后一列序号
privatestaticintend=0;
publicstaticStringgetSubString(Stringstr){
returnstr.substring(0,str.lastIndexOf("."));
}
/**
*方法描述:由Excel文件的Sheet导出至List
*@paramfile
*@paramsheetNum
*@return
*@throwsIOException
*@author
*@date2013-3-25下午10:44:26
*@comment
*/
publicstaticList<?>exportListFromExcel(Filefile,StringfileFormat,Objectdtoobj)
throwsIOException{
returnexportListFromExcel(newFileInputStream(file),fileFormat,dtoobj);
}
/**
*方法描述:由Excel流的Sheet导出至List
*@paramis
*@paramextensionName
*@paramsheetNum
*@return
*@throwsIOException
*@author
*@date2013-3-25下午10:44:03
*@comment
*/
publicstaticList<?>exportListFromExcel(InputStreamis,StringfileFormat,Objectdtoobj)throwsIOException{
Workbookworkbook=null;
if(fileFormat.equals(BizConstant.XLS)){
workbook=newHSSFWorkbook(is);
}elseif(fileFormat.equals(BizConstant.XLSX)){
workbook=newXSSFWorkbook(is);
}
returnexportListFromExcel(workbook,dtoobj);
}
/**
*方法描述:由指定的Sheet导出至List
*@paramworkbook
*@paramsheetNum
*@return
*@author
*@date2013-3-25下午10:43:46
*@comment
*/
privatestaticList<Object>exportListFromExcel(Workbookworkbook,Objectdtoobj){
List<Object>list=newArrayList<Object>();
String[]model=null;
Sheetsheet=workbook.getSheetAt(0);
//解析公式结果
FormulaEvaluatorevaluator=workbook.getCreationHelper().createFormulaEvaluator();
intminRowIx=sheet.getFirstRowNum();
intmaxRowIx=sheet.getLastRowNum();
for(introwIx=minRowIx;rowIx<=maxRowIx;rowIx++){
Objectobj=null;
if(rowIx==minRowIx){
start=sheet.getRow(rowIx).getFirstCellNum();
end=sheet.getRow(rowIx).getLastCellNum();
}
Rowrow=sheet.getRow(rowIx);
StringBuildersb=newStringBuilder();
for(inti=start;i<end;i++){
Cellcell=row.getCell(newInteger(i));
CellValuecellValue=evaluator.evaluate(cell);
if(cellValue==null){
sb.append(BizConstant.SEPARATOR+null);
continue;
}
//经过公式解析,最后只存在Boolean、Numeric和String三种数据类型,此外就是Error了
//其余数据类型,根据官方文档,完全可以忽略
switch(cellValue.getCellType()){
caseCell.CELL_TYPE_BOOLEAN:
sb.append(BizConstant.SEPARATOR+cellValue.getBooleanValue());
break;
caseCell.CELL_TYPE_NUMERIC:
//这里的日期类型会被转换为数字类型,需要判别后区分处理
if(DateUtil.isCellDateFormatted(cell)){
sb.append(BizConstant.SEPARATOR+cell.getDateCellValue());
}else{
sb.append(BizConstant.SEPARATOR+cellValue.getNumberValue());
}
break;
caseCell.CELL_TYPE_STRING:
sb.append(BizConstant.SEPARATOR+cellValue.getStringValue());
break;
caseCell.CELL_TYPE_FORMULA:
break;
caseCell.CELL_TYPE_BLANK:
break;
caseCell.CELL_TYPE_ERROR:
break;
default:
break;
}
}
if(rowIx==minRowIx){
Stringindex=String.valueOf(sb);
Stringrealmodel=index.substring(1,index.length());
model=realmodel.split(",");
}else{
Stringindex=String.valueOf(sb);
Stringrealvalue=index.substring(1,index.length());
String[]value=realvalue.split(",");
//字段映射
try{
dtoobj=dtoobj.getClass().newInstance();
}catch(InstantiationExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
obj=reflectUtil(dtoobj,model,value);
list.add(obj);
}
}
returnlist;
}
/**
*方法描述:字段映射赋值
*@paramobjOne
*@paramlistName
*@paramlistVales
*@return
*@author
*@date2013-3-25下午10:53:43
*@comment
*/
@SuppressWarnings("deprecation")
privatestaticObjectreflectUtil(ObjectobjOne,String[]listName,
String[]listVales){
Field[]fields=objOne.getClass().getDeclaredFields();
for(inti=0;i<fields.length;i++){
fields[i].setAccessible(true);
for(intj=0;j<listName.length;j++){
if(listName[j].equals(fields[i].getName())){
try{
if(fields[i].getType().getName().equals(java.lang.String.class.getName())){
//Stringtype
if(listVales[j]!=null){
fields[i].set(objOne,listVales[j]);
}else{
fields[i].set(objOne,"");
}
}elseif(fields[i].getType().getName().equals(java.lang.Integer.class.getName())
||fields[i].getType().getName().equals("int")){
//Integertype
if(listVales[j]!=null){
fields[i].set(objOne,(int)Double.parseDouble(listVales[j]));
}else{
fields[i].set(objOne,-1);
}
}elseif(fields[i].getType().getName().equals("Date")){
//datetype
if(listVales[j]!=null){
fields[i].set(objOne,Date.parse(listVales[j]));
}
}elseif(fields[i].getType().getName().equals("Double")
||fields[i].getType().getName().equals("float")){
//double
if(listVales[j]!=null){
fields[i].set(objOne,Double.parseDouble(listVales[j]));
}else{
fields[i].set(objOne,0.0);
}
}
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
break;
}
}
}
returnobjOne;
}
}
|