欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android通过jxl读excel存入sqlite3数据库

程序员文章站 2022-06-10 19:12:26
复制代码 代码如下:package com.demo.day20140228; import java.io.file;import java.sql.connectio...

复制代码 代码如下:

package com.demo.day20140228;

import java.io.file;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.sqlexception;
import java.sql.statement;

import jxl.cell;
import jxl.sheet;
import jxl.workbook;

public class dictexceldemo {
 public static void main(string[] args) {
  dictexceldemo ded = new dictexceldemo();
  connection conn = ded.getconnection();
  ded.readexcel_(conn);
 }

 private connection getconnection(){
  connection conn = null;
  try {
   class.forname("org.sqlite.jdbc");
   conn = drivermanager.getconnection("jdbc:sqlite:database.db");
   statement stat = conn.createstatement();
   stat.executeupdate("create  table if not exists dictionary(enword varchar(200), cnword varchar(200));");// 创建一个表,两列

  } catch (classnotfoundexception e) {
   e.printstacktrace();
  } catch (sqlexception e) {
   e.printstacktrace();
  }
  return conn;
 }

 private void readexcel_(connection conn) {
  try {
   workbook book = workbook.getworkbook(new file("english.xls"));
   preparedstatement prep = conn.preparestatement("insert into dictionary(enword,cnword) values(?,?);");

   for (int a = 0; a < 26; a++) {
    // 获得第一个工作表对象
    sheet sheet = book.getsheet(a);
    // 得到第一列第一行的单元格
    // 得到第一列第一行的单元格
    int columnum = sheet.getcolumns();// 得到列数
    int rownum = sheet.getrows();// 得到行数
    for (int i = 1; i < rownum; i++)// 循环进行读写
    {// 行
     string key = "";
     string value = "";
     for (int j = 0; j < columnum; j++) {// 列
      cell cell1 = sheet.getcell(j, i);
      string result = cell1.getcontents();
      if (j == 0) {
       key += result;
      } else {
       value += result;
      }
     }
     // system.out.println(key+"=="+value);
     prep.setstring(1, key);
     prep.setstring(2, value);
     prep.addbatch();
    }
   }
   conn.setautocommit(false);
   prep.executebatch();
   conn.setautocommit(true);
   conn.close();
   book.close();
  } catch (exception e) {
   system.out.println(e);
  }
 }
}