当前位置: 移动技术网 > IT编程>开发语言>Java > Java用jxl读取excel并保存到数据库的方法

Java用jxl读取excel并保存到数据库的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

028成都交友网,一起走过的日子吉他谱,www.49vv.con

项目中涉及到读取excel中的数据,保存到数据库中,用jxl做起来比较简单。

基本的思路:

把excel放到固定盘里,然后前段页面选择文件,把文件的名字传到后台,再利用jxl进行数据读取,把读取到的数据存到list中,通过遍历list,得到map,存到数据库中。

首先导入jar包:在网上都有,

代码:

页面:

新模excel导入

<input type="file" name="excel" id="xinmu">
<input type="button" id="newmj" value="导入">

js

//通过ajax进行操作
$(function(){
   $("#newmj").click(function(){
    alert("haha");
    $.ajax({
     url:'${pagecontext.request.contextpath}/uploadexcelservlet?type=xinmu&filename='+$("#xinmu").val(),
     type:'get',
     success:function(result){
      //alert("haha");
      alert(result);
       var json= eval('(' + result + ')');
              }
    })
   })
  }); 

servlet

 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  //request.setcharacterencoding("utf-8");
  system.out.println("jinru");
  string type=request.getparameter("type");
  string filename=request.getparameter("filename");
  //system.out.println(filename);
  file file = new file("d:\\"+filename);// 表格存储的位置
  jsonobject jsonobject = new jsonobject();
  //记录一下文件是否存在
  if (file.exists()) {
   jsonobject.put("exist", "文件存在");
   list<map<string, string>>list=readexcel.readexcel(file);
   mujuservice mjservice = new mujuservice();
   for (map<string, string> map : list) {
    jsonobject = mjservice.addnewmuju(map);
   }
   
  } else {
   jsonobject.put("exist", "文件不存在");
   system.out.println("文件不存在");
  }
  
 
 }

jxl处理类

import java.io.file;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import jxl.cell;
import jxl.sheet;
import jxl.workbook;

public class readexcel {
 
 public static list<map<string,string>> readexcel(file file){
  list<map<string, string>>list =new arraylist<map<string,string>>();
  try {
   // 判断文件是否存在
    // 创建工作簿
    workbook workbook = workbook.getworkbook(file);
    // 获得第一个工作表sheet1
    sheet sheet = workbook.getsheet(0);
    // 获得数据
    for (int i = 1; i < sheet.getrows(); i++) {// sheet.getrows():获得表格文件行数
     map<string, string>map = new hashmap<string, string>();
     for (int j = 0; j < sheet.getcolumns(); j++) {// sheet.getcolumns():获得表格文件列数
      cell cell = sheet.getcell(j, i);
     // system.out.print(cell.getcontents() + " ");
      map.put(sheet.getcell(j,0).getcontents(), cell.getcontents());
      //(列,行)
     }
     //system.out.println("");// 换行
     list.add(map);
    }
    //调用方法进行数据库的操作
    //.......
    system.out.println(list);
    workbook.close();// 关闭
   } catch (exception e) {
    e.printstacktrace();
   }
  return list;
 }
}

如此就能完成了,但是值得注意的是,我现在写的这段代码,无法自由选择文件路径进行读取,excel必须放在固定盘里。excel后缀必须是.xls,所以wps的excel不可用,而且文件名字不可以是中文。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网