--------------------------------------------------------------------------------------------------------
1、数据插入表结构:
2、Excel文件数据:
3.完整代码:
package oracleTestProject;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ReadExcel {
static Connection conn = null;
public static void main(String[] args) throws Exception{
File file = new File("F:/study/20190713/test.xls");
dataBaseConnection();
excel2DataBase(file);
}
/**
* 数据库连接
* @throws Exception
*/
public static void dataBaseConnection() throws Exception{
System.out.println("连接数据库开始......");
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","Deng123456");
System.out.println("连接数据库成功......");
}
/**
* 读取Excel文件数据插入数据库
* @param file
* @throws Exception
*/
public static void excel2DataBase(File file) throws Exception{
System.out.println("读取Excel文件开始......");
String sSql = "";//SQL语句
String sInsertColName = "";
String sInsertColValue = "";
Statement st = null;
try{
//插入数据表列名,第一个为空,抵消Excel表格第一列序号,使遍历时下标对应
String[] sColName = {"","Stu_No","Stu_Name","Stu_Age","Stu_Sex","Stu_Qq","Stu_Phone","Stu_Addr"};
FileInputStream fileInputStream = new FileInputStream(file);
jxl.Workbook rwb = Workbook.getWorkbook(fileInputStream);
Sheet sheet = rwb.getSheet(0);//取第一个 工作表
for (int i = 1; i < sheet.getRows(); i++) {//第一行为表头,从第二行开始读取
Cell[] cells = sheet.getRow(i);
sInsertColName = "";//每读一行都要置空
sInsertColValue = "";//每读一行都要置空
for(int j = 1; j < cells.length; j++){//第一列为序号,从第二列开始遍历
if(cells[j].getContents() != null && !"".equals(cells[j].getContents())){
sInsertColName += sColName[j]+",";
sInsertColValue += "'"+cells[j].getContents().trim()+"',";
}
}
if(!"".equals(sInsertColName)){
sInsertColName = sInsertColName.substring(0, sInsertColName.length()-1);
sInsertColValue = sInsertColValue.substring(0, sInsertColValue.length()-1);
sSql = " insert into student_temp ("+sInsertColName+") values("+sInsertColValue+") ";
st = conn.createStatement();
st.executeUpdate(sSql);
}
}
fileInputStream.close();
}catch(Exception e){
e.printStackTrace();
}
if(st != null){
st.close();
}
if(conn != null){
conn.close();
}
System.out.println("读取Excel文件结束......");
}
}
4、执行结果:
插入数据库的数据: