这篇文章主要为大家详细介绍了java用jxl读取excel并保存到数据库的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
项目中涉及到读取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不可用,而且文件名字不可以是中文。
以上就是java如何使用jxl读取excel且保存到数据库的方法实例的详细内容。