本文实例讲述了JSP上传excel及excel插入至数据库的方法。分享给大家供大家参考。具体如下:
此导入excel是与pojo绑定的,(缺点)excle表头必须是pojo的字段值
html
<
form
id
=
"myform"
method
=
"post"
enctype
=
"multipart/form-data"
>
<
table
>
<
tr
>
<
td
></
td
>
<
td
>
<
input
type
=
"file"
name
=
"filepath"
id
=
"filepath"
class
=
"easyui-validatebox"
required
=
true
validType
=
"equalLength[4]"
missingMessage
=
"文件!"
value
=
""
/>
</
td
>
</
tr
>
<
tr
align
=
"center"
>
<
td
colspan
=
"2"
>
<
a
id
=
"btn1"
class
=
"easyui-linkbutton"
data-options
=
"iconCls:'icon-ok'"
style
=
"width: 60px"
onclick
=
"subForm();"
>OK</
a
>
<
a
id
=
"btn2"
class
=
"easyui-linkbutton"
data-options
=
"iconCls:'icon-cancel'"
style
=
"width: 60px"
onclick
=
"closeDig();"
>Cancel</
a
>
</
td
>
</
tr
>
</
table
>
</
form
>
<
script
type
=
"text/javascript"
>
function subForm(){
if($('#myform').form('validate')){
/**
var filepath = $("#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");
}
});
**/
var filepath = $("#filepath").val();
var re = /(\\+)/g;
var filename = filepath.replace(re,"#");
//对路径字符串进行剪切截取
var one = filename.split("#");
//获取数组中最后一个,即文件名
var two = one[one.length-1];
//再对文件名进行截取,以取得后缀名
var three = two.split(".");
//获取截取的最后一个字符串,即为后缀名
var last = three[three.length-1];
//添加需要判断的后缀名类型
var tp = "xls,xlsx";
//返回符合条件的后缀名在字符串中的位置
var rs = tp.indexOf(last);
if(rs != -1){
$("#myform").attr("action","excleImport");
$("#myform").submit();
}else{
$.messager.alert("操作提示", "您选择的上传文件不是有效xls或者xlsx文件!","error");
return false;
}
} else {
$.messager.alert("操作提示", "请选择上传文件!","error");
}
}
</
script
>
java 代码
@RequestMapping
(
"/excleImport"
)
public
void
excleImport(HttpServletRequest request)
throws
IOException, Exception {
request.setCharacterEncoding(
"utf-8"
);
//设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory =
new
DiskFileItemFactory();
//获取文件需要上传到的路径
String path = request.getRealPath(
"/upload/kaku"
);
File uploadDir =
new
File(path);
if
(!uploadDir.exists()) {
uploadDir.mkdirs();
}
factory.setRepository(uploadDir);
//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(
1024
*
1024
) ;
//高水平的API文件上传处理
ServletFileUpload upload =
new
ServletFileUpload(factory);
//可以上传多个文件
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
for
(FileItem item : list)
{
//获取表单的属性名字
String name = item.getFieldName();
//如果获取的 表单信息是普通的 文本 信息
if
(item.isFormField())
{
//获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
String value = item.getString() ;
request.setAttribute(name, value);
}
//对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
else
{
/**
* 以下三步,主要获取 上传文件的名字
*/
//获取路径名
String value = item.getName() ;
//索引到最后一个反斜杠
int
start = value.lastIndexOf(
"\\"
);
//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start+
1
);
//文件后缀名
String prefix = filename.substring(filename.lastIndexOf(
"."
) +
1
);
CardCenter cardCenter =
new
CardCenter();
request.setAttribute(name, filename);
//真正写到磁盘上
//它抛出的异常 用exception 捕捉
//item.write( new File(path,filename) );//第三方提供的
//手动写的
//OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = item.getInputStream() ;
List<CardCenter> listFromExcel = (List<CardCenter>)ExelUtil.exportListFromExcel(in, prefix, cardCenter);
this
.cardCenterService.excleImport(listFromExcel);
/*int length = 0 ;
byte [] buf = new byte[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();
}
}
}
java代码
public
class
ExelUtil {
//第一列开始
private
static
int
start =
0
;
//最后一列序号
private
static
int
end =
0
;
public
static
String getSubString(String str){
return
str.substring(
0
,str.lastIndexOf(
"."
));
}
/**
* 方法描述:由Excel文件的Sheet导出至List
* @param file
* @param sheetNum
* @return
* @throws IOException
* @author
* @date 2013-3-25 下午10:44:26
* @comment
*/
public
static
List<?> exportListFromExcel(File file, String fileFormat,Object dtoobj)
throws
IOException {
return
exportListFromExcel(
new
FileInputStream(file), fileFormat,dtoobj);
}
/**
* 方法描述:由Excel流的Sheet导出至List
* @param is
* @param extensionName
* @param sheetNum
* @return
* @throws IOException
* @author
* @date 2013-3-25 下午10:44:03
* @comment
*/
public
static
List<?> exportListFromExcel(InputStream is,String fileFormat,Object dtoobj)
throws
IOException {
Workbook workbook =
null
;
if
(fileFormat.equals(BizConstant.XLS)) {
workbook =
new
HSSFWorkbook(is);
}
else
if
(fileFormat.equals(BizConstant.XLSX)) {
workbook =
new
XSSFWorkbook(is);
}
return
exportListFromExcel(workbook,dtoobj);
}
/**
* 方法描述:由指定的Sheet导出至List
* @param workbook
* @param sheetNum
* @return
* @author
* @date 2013-3-25 下午10:43:46
* @comment
*/
private
static
List<Object> exportListFromExcel(Workbook workbook ,Object dtoobj) {
List<Object> list =
new
ArrayList<Object>();
String[] model =
null
;
Sheet sheet = workbook.getSheetAt(
0
);
// 解析公式结果
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
int
minRowIx = sheet.getFirstRowNum();
int
maxRowIx = sheet.getLastRowNum();
for
(
int
rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
Object obj =
null
;
if
(rowIx==minRowIx){
start = sheet.getRow(rowIx).getFirstCellNum();
end = sheet.getRow(rowIx).getLastCellNum();
}
Row row = sheet.getRow(rowIx);
StringBuilder sb =
new
StringBuilder();
for
(
int
i = start; i < end; i++) {
Cell cell = row.getCell(
new
Integer(i));
CellValue cellValue = evaluator.evaluate(cell);
if
(cellValue ==
null
) {
sb.append(BizConstant.SEPARATOR+
null
);
continue
;
}
// 经过公式解析,最后只存在Boolean、Numeric和String三种数据类型,此外就是Error了
// 其余数据类型,根据官方文档,完全可以忽略
switch
(cellValue.getCellType()) {
case
Cell.CELL_TYPE_BOOLEAN:
sb.append(BizConstant.SEPARATOR + cellValue.getBooleanValue());
break
;
case
Cell.CELL_TYPE_NUMERIC:
// 这里的日期类型会被转换为数字类型,需要判别后区分处理
if
(DateUtil.isCellDateFormatted(cell)) {
sb.append(BizConstant.SEPARATOR + cell.getDateCellValue());
}
else
{
sb.append(BizConstant.SEPARATOR + cellValue.getNumberValue());
}
break
;
case
Cell.CELL_TYPE_STRING:
sb.append(BizConstant.SEPARATOR + cellValue.getStringValue());
break
;
case
Cell.CELL_TYPE_FORMULA:
break
;
case
Cell.CELL_TYPE_BLANK:
break
;
case
Cell.CELL_TYPE_ERROR:
break
;
default
:
break
;
}
}
if
(rowIx==minRowIx){
String index = String.valueOf(sb);
String realmodel =index.substring(
1
, index.length());
model =realmodel.split(
","
);
}
else
{
String index = String.valueOf(sb);
String realvalue =index.substring(
1
, index.length());
String[] value =realvalue.split(
","
);
//字段映射
try
{
dtoobj =dtoobj.getClass().newInstance();
}
catch
(InstantiationException e) {
e.printStackTrace();
}
catch
(IllegalAccessException e) {
e.printStackTrace();
}
obj = reflectUtil(dtoobj,model,value);
list.add(obj);
}
}
return
list;
}
/**
* 方法描述:字段映射赋值
* @param objOne
* @param listName
* @param listVales
* @return
* @author
* @date 2013-3-25 下午10:53:43
* @comment
*/
@SuppressWarnings
(
"deprecation"
)
private
static
Object reflectUtil(Object objOne, String[] listName,
String[] listVales) {
Field[] fields = objOne.getClass().getDeclaredFields();
for
(
int
i =
0
; i < fields.length; i++) {
fields[i].setAccessible(
true
);
for
(
int
j =
0
; j < listName.length; j++) {
if
(listName[j].equals(fields[i].getName())) {
try
{
if
(fields[i].getType().getName().equals(java.lang.String.
class
.getName())) {
// String type
if
(listVales[j]!=
null
){
fields[i].set(objOne, listVales[j]);
}
else
{
fields[i].set(objOne,
""
);
}
}
else
if
(fields[i].getType().getName().equals(java.lang.Integer.
class
.getName())
|| fields[i].getType().getName().equals(
"int"
)) {
// Integer type
if
(listVales[j]!=
null
){
fields[i].set(objOne, (
int
)Double.parseDouble(listVales[j]));
}
else
{
fields[i].set(objOne, -
1
);
}
}
else
if
(fields[i].getType().getName().equals(
"Date"
)){
//date type
if
(listVales[j]!=
null
){
fields[i].set(objOne, Date.parse(listVales[j]));
}
}
else
if
(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
(IllegalArgumentException e) {
e.printStackTrace();
}
catch
(IllegalAccessException e) {
e.printStackTrace();
}
break
;
}
}
}
return
objOne;
}
}