java从前端获取excel表并进行解析,将数据保存数据库
2018-03-21 16:12
483 查看
前端一个简单的上传例子
<div class="actionItems">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="functop" id="defaultOption"><h3>上传考试结果</h3></td>
</tr>
<tr id="openclose">
<td class="func">
<form id="fileform" enctype="multipart/form-data" action="file_upload.do" method="post">
<input type="file" name="descore" value="请选择文件"/>
<input type="submit" value="上传" />
</form>
</td>
</tr>
</tbody>
</table>
</div>
后台获取excel表格,并对excel表格进行解析保存
@RequestMapping(value = "/shopadmin/designer_examine_upload.do", method = RequestMethod.POST, produces = "application/json")
public void designerexamineupload(WebRequest webRequest,
ModelMap model, HttpServletRequest request,HttpServletResponse response) {
String savePath = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(savePath);
if(!file.exists()&&!file.isDirectory()){
System.out.println("目录或文件不存在!");
file.mkdir();
}
//消息提示
String message = "";
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multipartRequest.getFileNames();
while (iter.hasNext()) {
String filefiled = iter.next();
MultipartFile multipartFile = multipartRequest.getFile(filefiled);
BufferedInputStream in = new BufferedInputStream(multipartFile.getInputStream());//获得文件输入流
String srcName = multipartFile.getOriginalFilename();
String ext = getExtention(srcName);//获得后缀名
String filename = UUID.randomUUID() +"." + ext;//生成新的文件名
File f = new File(savePath);
if(!f.exists()){
f.mkdirs();
}
new File(savePath).mkdirs();//如果路径存在就使用,不存在就创建
String filelocation = savePath + "/" + filename;//文件存放的绝对路径
this.SaveInputToFile(in, filelocation);//文件上传
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filelocation));
//按名引用excel工作表
//也可以用以下方式来获取excel的工作表,采用工作表的索引值
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row ;
XSSFCell cell1,cell2;
int rows=sheet.getLastRowNum();
List<Map<String, Object>> l=new ArrayList<Map<String, Object>>();
System.out.println(rows);
for(int icount=1;icount<=rows;icount++){
//System.out.println(icount);
row = sheet.getRow(icount);
cell1= row.getCell(0);
cell2=row.getCell(1);
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
String shopname=(cell1.getStringCellValue()).trim();
String score=(cell2.getStringCellValue()).trim();
long shopid=jdbc.queryForObject("select id from biz_shop where shopname =?",new Object[]{shopname},Long.class);
long levelid=jdbc.queryForObject("select id from biz_designer_examine_level where ? between"
+ " minpoints and maxpoints",new Object[]{Float.valueOf(score)},Long.class);
List<DesignerExamine> dl=dao.find("from DesignerExamine where shopId=?",shopid);
if(dl.size()>0){
DesignerExamine d=dl.get(0);
d.setCreatetime(new Date());
d.setExamineLevelId(levelid);
d.setPoints(Float.valueOf(score));
d.setShopId(shopid);
d.setShopName(shopname);
dao.merge(d);
}else{
DesignerExamine d=new DesignerExamine();
d.setCreatetime(new Date());
d.setExamineLevelId(levelid);
d.setPoints(Float.valueOf(score));
d.setShopId(shopid);
d.setShopName(shopname);
dao.merge(d);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "文件上传失败";
}
try {
response.sendRedirect("/shopadmin/designer_examine.do");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获得文件后缀名的方法
public static String getExtention(String filename){
String ext = null;
int index = filename.lastIndexOf(".");//检索'.'在文件名字符串中的位置
if(index > 0){
ext = filename.substring(index + 1).toLowerCase();//获得后缀并返回
}
return ext;
}
private boolean SaveInputToFile(BufferedInputStream inBuff,String targetpath){
boolean re=false;
BufferedOutputStream outBuff = null;
try{
outBuff = new BufferedOutputStream(new FileOutputStream(targetpath));//获得输出流
byte[] b = new byte[4096];
int len;
while((len = inBuff.read(b)) != -1){
outBuff.write(b, 0, len);
}
outBuff.flush();
re=true;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(inBuff != null)
inBuff.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(outBuff != null)
outBuff.close();
}catch(Exception e){
e.printStackTrace();
}
}
return re;
}
用到的解析Excel的jar包:poi-3.9-20121203.jar
<div class="actionItems">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="functop" id="defaultOption"><h3>上传考试结果</h3></td>
</tr>
<tr id="openclose">
<td class="func">
<form id="fileform" enctype="multipart/form-data" action="file_upload.do" method="post">
<input type="file" name="descore" value="请选择文件"/>
<input type="submit" value="上传" />
</form>
</td>
</tr>
</tbody>
</table>
</div>
后台获取excel表格,并对excel表格进行解析保存
@RequestMapping(value = "/shopadmin/designer_examine_upload.do", method = RequestMethod.POST, produces = "application/json")
public void designerexamineupload(WebRequest webRequest,
ModelMap model, HttpServletRequest request,HttpServletResponse response) {
String savePath = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(savePath);
if(!file.exists()&&!file.isDirectory()){
System.out.println("目录或文件不存在!");
file.mkdir();
}
//消息提示
String message = "";
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multipartRequest.getFileNames();
while (iter.hasNext()) {
String filefiled = iter.next();
MultipartFile multipartFile = multipartRequest.getFile(filefiled);
BufferedInputStream in = new BufferedInputStream(multipartFile.getInputStream());//获得文件输入流
String srcName = multipartFile.getOriginalFilename();
String ext = getExtention(srcName);//获得后缀名
String filename = UUID.randomUUID() +"." + ext;//生成新的文件名
File f = new File(savePath);
if(!f.exists()){
f.mkdirs();
}
new File(savePath).mkdirs();//如果路径存在就使用,不存在就创建
String filelocation = savePath + "/" + filename;//文件存放的绝对路径
this.SaveInputToFile(in, filelocation);//文件上传
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filelocation));
//按名引用excel工作表
//也可以用以下方式来获取excel的工作表,采用工作表的索引值
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row ;
XSSFCell cell1,cell2;
int rows=sheet.getLastRowNum();
List<Map<String, Object>> l=new ArrayList<Map<String, Object>>();
System.out.println(rows);
for(int icount=1;icount<=rows;icount++){
//System.out.println(icount);
row = sheet.getRow(icount);
cell1= row.getCell(0);
cell2=row.getCell(1);
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
String shopname=(cell1.getStringCellValue()).trim();
String score=(cell2.getStringCellValue()).trim();
long shopid=jdbc.queryForObject("select id from biz_shop where shopname =?",new Object[]{shopname},Long.class);
long levelid=jdbc.queryForObject("select id from biz_designer_examine_level where ? between"
+ " minpoints and maxpoints",new Object[]{Float.valueOf(score)},Long.class);
List<DesignerExamine> dl=dao.find("from DesignerExamine where shopId=?",shopid);
if(dl.size()>0){
DesignerExamine d=dl.get(0);
d.setCreatetime(new Date());
d.setExamineLevelId(levelid);
d.setPoints(Float.valueOf(score));
d.setShopId(shopid);
d.setShopName(shopname);
dao.merge(d);
}else{
DesignerExamine d=new DesignerExamine();
d.setCreatetime(new Date());
d.setExamineLevelId(levelid);
d.setPoints(Float.valueOf(score));
d.setShopId(shopid);
d.setShopName(shopname);
dao.merge(d);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "文件上传失败";
}
try {
response.sendRedirect("/shopadmin/designer_examine.do");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获得文件后缀名的方法
public static String getExtention(String filename){
String ext = null;
int index = filename.lastIndexOf(".");//检索'.'在文件名字符串中的位置
if(index > 0){
ext = filename.substring(index + 1).toLowerCase();//获得后缀并返回
}
return ext;
}
private boolean SaveInputToFile(BufferedInputStream inBuff,String targetpath){
boolean re=false;
BufferedOutputStream outBuff = null;
try{
outBuff = new BufferedOutputStream(new FileOutputStream(targetpath));//获得输出流
byte[] b = new byte[4096];
int len;
while((len = inBuff.read(b)) != -1){
outBuff.write(b, 0, len);
}
outBuff.flush();
re=true;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(inBuff != null)
inBuff.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(outBuff != null)
outBuff.close();
}catch(Exception e){
e.printStackTrace();
}
}
return re;
}
用到的解析Excel的jar包:poi-3.9-20121203.jar
相关文章推荐
- JAVA 根据URL获取JSON数据,并解析后存入数据库
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及文件上传的部分
- Java实现头像截取裁剪后图片保存,获取的是base64数据,怎么转换为图片并保存到数据库。
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及非文件上传的部分
- 通过JAVA从高德地图URL连接获取json数据 解析并存入数据库的程序举例
- 元数据(Java获取数据库中的元信息)及数据库表导出到Excel表(HSSF)
- java web 前端获取数据 数据库传值给前端显示
- Java解析Excel并把数据保存到数据库中
- Java实现头像截取裁剪后图片保存,获取的是base64数据,怎么转换为图片并保存到数据库。并读取出来。
- struts2 + ajax(从后台获取json格式的数据返回到前端,然后前端用jquery对json数据进行解析)
- Java实现头像截取裁剪后图片保存,获取的是base64数据,怎么转换为图片并保存到数据库。
- 《项目经验》--通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
- jsoup 解析html网页标签获取数据(java 网页解析 数据)
- java通过url获取页面数据 java解析xml 基金净值接口使用方法
- 如何对dataset中进行修改并把修改后的数据保存到数据库中?
- java对xml进行的DOM 解析以及如何对网站数据进行加密
- ASP.NET数据导入至页面列表进行查看并最终保存到数据库
- Silverlight调用自定义的Web Service从数据库获取数据进行页面绑定
- java中对JSON格式数据进行解析和映射
- java解析获取Excel中的数据--同时兼容2003及2007