java 读取excel文件到数据库

 首先 引入所需jar包 jxl.jar 注意一点的是jxl只支持excel2003的.xls文件 


代码如下:

package com.xlsx.jenna;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ReadXlsx {

private PreparedStatement ps;
private Connection conn;
private BaseOperate baseOperate = new BaseOperate();
public ReadXlsx(){
conn = baseOperate.getConn();
}
public void read(){
String path = "D:temp/test.xls";

try {
InputStream is = new FileInputStream(new File(path));

Workbook wb = Workbook.getWorkbook(is);
//取得第0个sheet
Sheet sheet = wb.getSheet(0);
//取得所有列
int columns = sheet.getColumns();
//取得所有行
int rows = sheet.getRows();

String sql = "insert into dateTO (name,age,sex,descri) values (?,?,?,?)";

ps = conn.prepareStatement(sql);

for(int i = 1; i < rows; i ++){
//取得第i行的所有单元格
Cell[] cell = sheet.getRow(i);
int j = 0;

//取得第J个单元格的内容
String name = cell[j].getContents();
j ++;
ps.setString(j, name);
int age = Integer.parseInt(cell[j].getContents());
j ++;
ps.setInt(j, age);
String sex = cell[j].getContents();
j ++;
ps.setString(j, sex);
String descri = cell[j].getContents();
ps.setString(j+1, descri);

ps.execute();
}
System.out.println("数据插入成功");
}catch(Exception e){
System.out.println("数据插入异常,请重试");
e.printStackTrace();
}
}

public static void main(String[] args) {
ReadXlsx rx = new ReadXlsx();
rx.read();
}

}  

你可能感兴趣的:(数据库,Excel)