1.jsp页面:
<form action="uptest.action" method="post" enctype="multipart/form-data" >
<th>
<input id="datafile" name="datafile" type="file" style="width: 240px; height: 21px" />
</th>
<th>
<input class="bottom_a" style="cursor: hand"
type="submit" value="上传 "
name="sub"
id="sub" />
</th>
</form>
<script language="javascript">
$("#sub").click(function(){
var file=$("#datafile").val();
alert(file);
var ext=file.substring(file.lastIndexOf(".")).toLowerCase();
if(file==null)
{
alert("请选择上传的附件");
return false;
}
else
{
if(ext!=".xlsx" && ext!=".xls" )
{
alert("此附件类型不支持:["+ext+"]");
return false;
}
}
return true;
});
</script>
java后台代码:
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public String uptest()
{
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
Integer successNum=0;
Integer totalNum=0;
try {
InputStream input = FileUtils.openInputStream(datafile);
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while(rows.hasNext()){
totalNum++;
HSSFRow row = (HSSFRow) rows.next();
if(row != null){
if(row.getRowNum() != 0){
//获取第一个单元格
HSSFCell cell_0 = row.getCell(0);
//获取第二个单元格
HSSFCell cell_1 = row.getCell(0);
if(null != cell_0){
//获取第一个单元格内容
String str1=cell_0.toString().trim();
System.out.println(str1);
}
if(null!=cell_1){
//获取第二个单元格内容
String str2=cell_0.toString().trim();
}
}
}
//此处是根据获取的值需要操作数据库的方法
}
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("成功更新"+(successNum)+"条,失败"+(totalNum-successNum-1)+"条");
} catch (UnsupportedEncodingException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
return SUCCESS;
}
浙公网安备 33010602011771号