java读取ecxel文件 并写入oracle数据库

package com.icss.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**

* java读取excel文件
*
* 一个Excel文件的层次:Excel文件->工作表->行->单元格 对应到POI中,为:workbook->sheet->row->cell

*/
public class exlFile {
 public static String outputFile = "E:\\NQ_SCHEDULE_INFO.xls";

 public static String fileToBeRead = "E:\\NQ_SCHEDULE_INFO.xls";

 public void CreateExcel() {
   try {
   // 创建新的Excel 工作簿
   HSSFWorkbook workbook = new HSSFWorkbook();
   // 在Excel工作簿中建一工作表,其名为缺省值
   // 如要新建一名为"效益指标"的工作表,其语句为:
   // HSSFSheet sheet = workbook.createSheet("效益指标");
   HSSFSheet sheet = workbook.createSheet();
   // 在索引0的位置创建行(最顶端的行)
   HSSFRow row = sheet.createRow((short) 0);
   //在索引0的位置创建单元格(左上端)
   HSSFCell cell = row.createCell((short) 0);
   // 定义单元格为字符串类型
   cell.setCellType(HSSFCell.CELL_TYPE_STRING);
   // 在单元格中输入一些内容
   cell.setCellValue("sweater");
   // 新建一输出文件流
   FileOutputStream fOut = new FileOutputStream(outputFile);
   // 把相应的Excel 工作簿存盘
   workbook.write(fOut);
   fOut.flush();
   // 操作结束,关闭文件
   fOut.close();
   System.out.println("文件生成...");

   } catch (Exception e) {
   System.out.println("已运行 xlCreate() : " + e);
   }
 }

/**
  *
  * 读取excel,遍历各个小格获取其中信息,并判断其是否是手机号码,并对正确的手机号码进行显示
  *
  *
  * 注意: 1.sheet, 以0开始,以workbook.getNumberOfSheets()-1结束 2.row,
  * 以0开始(getFirstRowNum),以getLastRowNum结束 3.cell,
  * 以0开始(getFirstCellNum),以getLastCellNum结束, 结束的数目不知什么原因与显示的长度不同,可能会偏长
  * 
  */
public void readExcel() {
  //将被表示成1.3922433397E10的手机号转化为13922433397,不一定是最好的转换方法
  DecimalFormat df = new DecimalFormat("#");

  try {
  // 创建对Excel工作簿文件的引用
  HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
    fileToBeRead));
  //System.out
  //  .println("===SheetsNum===" + workbook.getNumberOfSheets());//获取sheet数
  for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
    if (null != workbook.getSheetAt(numSheets)) {
    HSSFSheet aSheet = workbook.getSheetAt(numSheets);//获得一个sheet
    //System.out.println("+++getFirstRowNum+++" +
    // aSheet.getFirstRowNum());//
    //System.out.println("+++getLastRowNum+++" +
    // aSheet.getLastRowNum());

    for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
      .getLastRowNum(); rowNumOfSheet++) {
      if (null != aSheet.getRow(rowNumOfSheet)) {
      HSSFRow aRow = aSheet.getRow(rowNumOfSheet);

      //System.out.println(">>>getFirstCellNum < < <"+
      // aRow.getFirstCellNum());
      //System.out.println(">>>getLastCellNum < < <"+
      // aRow.getLastCellNum());
      for (short cellNumOfRow = 0; cellNumOfRow <= aRow
        .getLastCellNum(); cellNumOfRow++) {

        if (null != aRow.getCell(cellNumOfRow)) {
        HSSFCell aCell = aRow.getCell(cellNumOfRow);

        int cellType = aCell.getCellType();
        System.out.println(cellNumOfRow+"     cellType :"+cellType);
        switch (cellType) {
        case 0://Numeric
          String strCell = df.format(aCell
            .getNumericCellValue());

          System.out.println("strCell0===============:"+strCell);
         

          break;
        case 1://String
          strCell = aCell.getStringCellValue();

          System.out.println("strCell1¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥:"+strCell);
         

          break;
        default:
        System.out.println("格式不对不读");//其它格式的数据
        }

        }

      }
      }

    }

    }

  }

  } catch (Exception e) {
  System.out.println("ReadExcelError" + e);
  }

}

  public static void main(String[] args) throws SQLException {
  

   try {
  //1. 连接Oracle 8/8i/9i的驱动程序:
  Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();    
     //2. 建立连接:
  Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.30.150:1521:orcl","JNNQ","JNNQ");
        //
  Statement sm=con.createStatement();
  //String sql="insert into nq_schedule_info names(REPORT_ID,REPORT_CODE,TBY,TBR, COMMENTT)values (?,?,?,?,?)";
  //seq_product.nextval
  String sql="insert into nq_schedule_info values (nq_schedule_info_sequence.nextval,?,?,?,?,?)";
  
  PreparedStatement pst=con.prepareStatement(sql);
  
    //将被表示成1.3922433397E10的手机号转化为13922433397,不一定是最好的转换方法
    DecimalFormat df = new DecimalFormat("#");

    try {
    // 创建对Excel工作簿文件的引用
    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
      fileToBeRead));
    //System.out
    //  .println("===SheetsNum===" + workbook.getNumberOfSheets());//获取sheet数
    for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
      if (null != workbook.getSheetAt(numSheets)) {
      HSSFSheet aSheet = workbook.getSheetAt(numSheets);//获得一个sheet
      //System.out.println("+++getFirstRowNum+++" +
      // aSheet.getFirstRowNum());//
      //System.out.println("+++getLastRowNum+++" +
      // aSheet.getLastRowNum());

        int p1=0,p4 = 0,p3=0,p0 = 0;
        String s2 = null,s5=null;
      for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
        .getLastRowNum(); rowNumOfSheet++) {
        if (null != aSheet.getRow(rowNumOfSheet)) {
        HSSFRow aRow = aSheet.getRow(rowNumOfSheet);

        //System.out.println(">>>getFirstCellNum < < <"+
        // aRow.getFirstCellNum());
        //System.out.println(">>>getLastCellNum < < <"+
        // aRow.getLastCellNum());

       
        for (short cellNumOfRow = 0; cellNumOfRow <= aRow
          .getLastCellNum(); cellNumOfRow++) {

          if (null != aRow.getCell(cellNumOfRow)) {
          HSSFCell aCell = aRow.getCell(cellNumOfRow);

          int cellType = aCell.getCellType();
          String strCell;
          System.out.println(cellNumOfRow+"     cellType :+++++++++++++++"+cellType);
          switch (cellType) {
          case 0://Numeric
             strCell = df.format(aCell
              .getNumericCellValue());

            System.out.println("strCell0===============:"+strCell);
            if(0==cellNumOfRow) p0=Integer.parseInt(strCell);
            if(1==cellNumOfRow) p1=Integer.parseInt(strCell);
            if(3==cellNumOfRow) p3=Integer.parseInt(strCell);
            if(4==cellNumOfRow) p4=Integer.parseInt(strCell);
            break;
          case 1://String
            strCell = aCell.getStringCellValue();

            System.out.println("strCell1¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥:"+strCell);
            if(2==cellNumOfRow) s2=strCell;
            if(5==cellNumOfRow) s5=strCell;

            break;
          default:
         if(0==cellNumOfRow) p0=0;
            if(1==cellNumOfRow) p1=0;
            if(3==cellNumOfRow) p3=0;
            if(4==cellNumOfRow) p4=0;
            if(2==cellNumOfRow) s2="0";
            if(5==cellNumOfRow) s5="0";
 
          System.out.println("格式不对不读");//其它格式的数据
         
          }

          }

        }
        System.out.println("pppppppppppppppppppppppppppp"+p0+"  "+p1+"  "+p3+"  "+p4+"  "+s2+"  "+s5+"  ");
        //pst.setInt(0,  "");
        pst.setInt(1, p1);
        pst.setString(2, s2);
        pst.setInt(3, p3);
        pst.setInt(4, p4);
        pst.setString(5, s5);
        pst.execute();
        con.commit();
        }

      }

      }

    }

    } catch (Exception e) {
     System.out.println("????????");
    System.out.println("ReadExcelError" + e);
    }
  
  ResultSet rs=sm.executeQuery(sql);
  while (rs.next())
  {
   //对结果的处理
  }
  rs.close();
  sm.close();
  con.close();
 
   } catch (InstantiationException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IllegalAccessException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

   exlFile poi = new exlFile();
  //poi.CreateExcel();
  poi.readExcel();

}
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个相对较复杂的问题,需要分几个步骤来实现。 1. 使用Java读取Excel文件 可以使用Apache POI这个库来读取Excel文件,具体实现如下: ```java FileInputStream inputStream = new FileInputStream(new File("path/to/excel/file.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); //获取第一个工作表 for (Row row : sheet) { //遍历每一行 for (Cell cell : row) { //遍历每一个单元格 String cellValue = cell.getStringCellValue(); //将cellValue添加到对应的数据结构 } } workbook.close(); inputStream.close(); ``` 2. 异步导入数据库 可以使用Java的ExecutorService来实现异步操作,具体实现如下: ```java ExecutorService executorService = Executors.newFixedThreadPool(10); //创建一个线程池,最多有10个线程同时执行任务 for (Object data : dataList) { executorService.submit(() -> { //将数据异步导入数据库 }); } executorService.shutdown(); //关闭线程池 ``` 3. 自动生成代码 可以使用MyBatis Generator这个工具来自动生成代码,具体实现如下: 1. 编写一个XML文件,描述数据库的表结构和生成的Java类的属性、方法等信息。 2. 编写一个Java类,调用MyBatis Generator提供的API来生成代码。 这里给出一个简单的XML文件示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="mysql" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password=""> </jdbcConnection> <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="student" domainObjectName="Student"/> </context> </generatorConfiguration> ``` 然后编写一个Java类,调用MyBatis Generator提供的API来生成代码: ```java List<String> warnings = new ArrayList<>(); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(new File("path/to/mybatis/generator.xml")); DefaultShellCallback callback = new DefaultShellCallback(true); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); ``` 以上就是实现Java读取Excel文件并异步导入数据库生成代码的大致流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值