javaexcel数据导入数据库中
用到的类 是 :
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
try {
// List<String[]> 中的元素 行数组String[]为excel中的每一行
List<String[]> list = new ArrayList<String[]>();
InputStream is = new FileInputStream("test.xls");
HSSFWorkbook hwk = new HSSFWorkbook(is);// 将is流实例到 一个excel流里
HSSFSheet sh = hwk.getSheetAt(0);// 得到book第一个工作薄sheet
int rows = sh.getLastRowNum()+1 - sh.getFirstRowNum(); // 总行数
for(int i=0; i<rows; i++){
HSSFRow row = sh.getRow(i);
int cols = row.getLastCellNum()+1 - row.getFirstCellNum(); // 该行的总列数
String[] str = new String[cols]; // 用来存放该行每一列的值
for (int j = 0; j < cols; j++) {
Object col = row.getCell((short)j);
str[j] = col.toString();
}
}
......
......
循环变量 i 和 j 可以自己设定从第几行开始读,第几列开始读,下标从0开始。
然后你想做什么判断想做什么数据匹配都可以自己加了。
poi.hssf.usermodel.* jar包要是网上找不到,就给我发邮件,我邮给你:[email protected]
㈡ 如何用Java将excel数据导入数据库
package com.javen.excel;
import java.util.List;
import com.javen.db.DBhepler;
import com.javen.entity.StuEntity;
import com.javen.service.StuService;
/**
* @author Javen
* @Email [email protected]
*
*/
public class TestExcelToDb {
public static void main(String[] args) {
//得到表格中所有的数据
List<StuEntity> listExcel=StuService.getAllByExcel("d://book.xls");
/*//得到数据库表中所有的数据
List<StuEntity> listDb=StuService.getAllByDb();*/
DBhepler db=new DBhepler();
for (StuEntity stuEntity : listExcel) {
int id=stuEntity.getId();
if (!StuService.isExist(id)) {
//不存在就添加
String sql="insert into stu (name,sex,num) values(?,?,?)";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+""};
db.AddU(sql, str);
}else {
//存在就更新
String sql="update stu set name=?,sex=?,num=? where id=?";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+"",id+""};
db.AddU(sql, str);
}
}
}
}
㈢ java中怎么把excel导入数据库
1、利用Excel第三方工具,将Excel文件读取到内存中。使用最简单,方便的工具是apache的poi工具包,自己网上下载http://poi.apache.org/,使用方法网上一搜一大片。
2、如果是对于特别大的excel(大于20M的话),简单的读取方法就容易内存溢出了,需要采用流式读取的方式,参考http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
3、将已读入内存的Excel数据,整理成写数据库的数据结构,然后插入数据库。这部分工作应该不用介绍了,就是基本的数据库操作方法,与excel无关了