将excel数据导入oracle中

近日做的项目中需要实现每天定时将excel的数据导入到oracle中,在网上查找了相关资料,最后决定用poi包来实现。 

poi包的下载地址大家可以在网上搜索一下,下载以后导入到我们的项目中去。

下面是实现代码:

package com.hdkj.ws;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.model.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;

import com.hdkj.pmis.util.*;
import java.io.FileInputStream;


public class GetDataFromExcel {

 public void importToDb(String sDate) {
  try {
   //String fileToBeRead ="D://jboss-dljy//ddjhdate//rjh_llx"+sDate+".xls";
   String fileToBeRead = "c://rjh_llx20071007.xls";
   String tempdate = sDate.substring(0, 4) + "-"
   + sDate.substring(4, 6) + "-"
   + sDate.substring(6, 8);
   if (fileToBeRead.equals(null)) {
    System.out.println("没有找到相应的excel文件");
   } else {
//    导入前先删除当天的数据
    String sqlu = "delete from jy_llx where d_jyrq='"+tempdate+"'";
    JdbcUtil.execute(sqlu);
    
    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
      fileToBeRead));
    HSSFSheet sheet = workbook.getSheetAt(0);
    int rows = sheet.getPhysicalNumberOfRows();
    for (int r = 4; r < rows; r++) {
     HSSFRow row = sheet.getRow(r);
     if (row != null) {
      int cells = row.getPhysicalNumberOfCells();
      String value = "";
      for (short c = 1; c < 31; c++) {
       HSSFCell cell = row.getCell(c);
       if (cell != null) {
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_FORMULA:
         //
         break;
        case HSSFCell.CELL_TYPE_NUMERIC:
         value += (long) cell.getNumericCellValue()
           + ",";
         break;
        case HSSFCell.CELL_TYPE_STRING:
         value += "'" + cell.getStringCellValue()
           + "'" + ",";
         break;
        default:
         value += "null,";

        }
       } 
      }
      
           // 加入交易时间
      value = value + "'" + tempdate + "'";

      // value = value.substring(0, value.length()-1);
      // 下面可以将查找到的行内容用SQL语句INSERT到oracle
      String sql = "insert into jy_llx(C_SK,C_CF,C_XZ,N_DLIANG,S1,S4,S8,S12,S16,S20,S24,S28,S32,S36,S40,S44,S48,S52,S56,S60,S64,S68,S72,S76,S80,S84,S88,S92,S96,C_JC,D_JYRQ,C_ID) values("
        + value + ",llx_id.nextval)";
      JdbcUtil.execute(sql);
     }
    }
    
    //删除电量为空的记录
    String sqldel = "delete from jy_llx where N_DLIANG is null and d_jyrq='"+tempdate+"'";
    JdbcUtil.execute(sqldel);
   }
  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

你可能感兴趣的:(excel,oracle,import,string,null,insert)