import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public
class
ExeclOperateMain {
public
static
void main(String[] args) throws Exception {
ExeclOperateMain e=
new
ExeclOperateMain();
e.getExcel();
System.out.println(
"Execl导入完成!"
);
}
public
Connection conn(){
try
{
Class.forName(
"oracle.jdbc.driver.OracleDriver"
);
Connection con =DriverManager.getConnection(
"jdbc:oracle:thin:@192.168.1.202:1521:orcl"
,
"mdb"
,
"mdb"
);
return
con;
}
catch
(ClassNotFoundException cnf){
System.out.println(
"驱动未找到!:"
+cnf);
return
null;
}
catch
(SQLException sqle){
System.out.println(
"不能连接数据库:"
+sqle);
return
null;
}
catch
(Exception e) {
System.out.println(
"加载失败 JDBC/ODBC driver."
);
return
null;
}
}
public
void getExcel() throws Exception {
HSSFWorkbook workbook =
new
HSSFWorkbook(
new
FileInputStream(
"E:\\Workspaces\\pt-zt-v1.0\\src\\test.xls"
));
for
(int i = 0; i < workbook.getNumberOfSheets(); i++) {
if
(workbook.getSheetAt(i).getPhysicalNumberOfRows()>0){
HSSFSheet childSheet = workbook.getSheetAt(i);
for
(int rowi=1;rowi<40000;rowi++){
if
(childSheet.getRow(rowi)==null)
break
;
String cell1=this.publicExcel(childSheet.getRow(rowi).getCell(0));
if
(cell1==null)
break
;
cell1=cell1.substring(0, cell1.length()-2);
String cell2=this.publicExcel(childSheet.getRow(rowi).getCell(1));
String cell3=this.publicExcel(childSheet.getRow(rowi).getCell(2));
String insert=
"insert into pt_zt values('"
+cell3+
"','"
+cell2+
"','"
+cell1+
"')"
;
System.out.println(
"SQL:"
+insert);
insert(insert);
}
}
}
}
public
String publicExcel( HSSFCell cell){
String value = null;
switch
(cell.getCellType()) {
case
HSSFCell.CELL_TYPE_NUMERIC:
value =
""
+ cell.getNumericCellValue();
break
;
case
HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break
;
case
HSSFCell.CELL_TYPE_BLANK:
;
break
;
default
:
}
return
value;
}
public
int insert(String insert) throws SQLException{
Connection conn = this.conn();
int re = 0;
try
{
conn.setAutoCommit(false);
Statement sm = conn.createStatement();
re = sm.executeUpdate(insert);
if
(re < 0){
conn.rollback();
sm.close();
conn.close();
return
re;
}
conn.commit();
System.out.println(
"一条已插入正常,sql="
+insert);
sm.close();
conn.close();
return
re;
}
catch
(Exception e){
e.printStackTrace();
}
conn.close();
return
0;
}
}