首页 > 编程知识 正文

poimysql数据库导入(poi导入excel到数据库)

时间:2023-12-20 16:55:07 阅读:318541 作者:ZQDV

本文目录一览:

java poi实现excel中的数据导入到mysql数据库中,例如excel中有id,name,age。将其导入到数据库中。

package bis.excel;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.TreeMap;

import jxl.Sheet;

import jxl.Workbook;

public class Excel {

 

 @SuppressWarnings("unchecked")

 public List addCust(File file){

  List list=new ArrayList();

  List list2=new ArrayList();

  Workbook rwb=null;

  try {

   List list1=new ArrayList();

   

   InputStream is=new FileInputStream(file);//读取文件(所要导入excel的保存目录,如:f:\a.xls)

   rwb=Workbook.getWorkbook(is);//创建工作薄

   Sheet rs=rwb.getSheet(0);//读取excel中的第一个工作表(默认新建excel下面有sheet1,sheet2,sheet3)

   int cellCount=rs.getColumns();//获取Sheet表中所包含的总列数

   int rowCount=rs.getRows();//获取Sheet表中所包含的总行数

   for(int m=0;mcellCount;m++){//将表的第一行数据保存到list1中(列名),即id,name ,age

    String cell=rs.getCell(m,0).getContents();

    list1.add(cell);

   }

   for(int i=1;irowCount;i++){//获取值

    Map map=new TreeMap();

    for(int j=0;jcellCount;j++){    

     map.put(list1.get(j),rs.getCell(j,i).getContents());//将值以键/值对方式保存到map对象中即(id:1,name:zhangsan,age:18)

    } 

    list.add(map);//将值保存到list中

    //System.out.println(list.get(i-1));

   }

   

   list2.add(list1);//将表头(id,name,age)保存到list2中

   list2.add(list);//将值保存到list2中

  } catch (Exception e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }finally{

   rwb.close();

  }

  return list2; 

 }

 public void tosql(){

  List list=addCust(file);//file:所要导入excel的保存目录,如:f:\a.xls

  Map map=new HashMap();

  String[] values=new String[ls2.size()];//保存id,name,age 值

  for (int i =0; i  ls2.size(); i++) { 

   map=(Map)ls2.get(i);

   String value="";

    id=(String)map.get("id");

   name=(String)map.get("name");

   age=(String)map.get("age");

   value=id+";"+name+";"+age;

   values[i]=value;

 }

 }

}

这是段读取excel表数据的代码,在tosql方法中调用addCust方法读取excel表,最后把所有行的id,name,age值保存到了values数组中,也可以保存到类中,如果你会对数据库操作的话,

后面的你自己弄下就行了,不会的话留言,我晚上在告诉你,我现在上班呢,时间有限,只能写这么多了

java通过poi把excel文件导入mysql数据库报错

java通过poi把excel文件导入mysql数据库报错是因为excel中的数据类型要跟mysql中的数据类型和长度对应,否则类型转换异常是最常见的。所以插入到mysql数据库的时候需要做类型检查。

1、Excel中的测试数据:

2、数据库表结构:

CREATE TABLE `student_info` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`no` varchar(20) DEFAULT NULL,

`name` varchar(20) DEFAULT NULL,

`age` varchar(10) DEFAULT NULL,

`score` float DEFAULT '0',

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3、java源码部分ReadExcel.java:

/**

* 读取excel中的数据并插入db

*/

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

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;

import com.b510.common.Common;

import com.b510.excel.vo.Student;

/**

* @author pieryon

* @created 2016-5-18

*/

public class ReadExcel {

  public ListStudent readXls() throws IOException {

      InputStream is = new FileInputStream(Common.EXCEL_PATH);

      HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

      Student student = null;

      ListStudent list = new ArrayListStudent();

      // 循环工作表Sheet

      for (int numSheet = 0; numSheet hssfWorkbook.getNumberOfSheets(); numSheet++) {

          HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);

          if (hssfSheet == null) {

              continue;

          }

          // 循环行Row

          for (int rowNum = 1; rowNum = hssfSheet.getLastRowNum(); rowNum++) {

              HSSFRow hssfRow = hssfSheet.getRow(rowNum);

              if (hssfRow != null) {

                  student = new Student();

                  HSSFCell no = hssfRow.getCell(0);

                  HSSFCell name = hssfRow.getCell(1);

                  HSSFCell age = hssfRow.getCell(2);

                  HSSFCell score = hssfRow.getCell(3);

                  student.setNo(getValue(no));

                  student.setName(getValue(name));

                  student.setAge(getValue(age));

                  student.setScore(Float.valueOf(getValue(score)));

                  list.add(student);

              }

          }

      }

      return list;

  }

   @SuppressWarnings("static-access")

  private String getValue(HSSFCell hssfCell) {

          if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {

              // 返回布尔类型的值

              return String.valueOf(hssfCell.getBooleanCellValue());

          } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {

              // 返回数值类型的值

              return String.valueOf(hssfCell.getNumericCellValue());

          } else {

              // 返回字符串类型的值

              return String.valueOf(hssfCell.getStringCellValue());

          }

      }

}

2、SaveData2DB.java

/**

* 插入数据到db

*/

import java.io.IOException;

import java.sql.SQLException;

import java.util.List;

import com.b510.common.Common;

import com.b510.excel.util.DbUtil;

import com.b510.excel.vo.Student;

/**

* @author pieryon

* @created 2016-5-18

*/

public class SaveData2DB {

  @SuppressWarnings({ "rawtypes" })

  public void save() throws IOException, SQLException {

      ReadExcel xlsMain = new ReadExcel();

      Student student = null;

      ListStudent list = xlsMain.readXls();

      for (int i = 0; i list.size(); i++) {

          student = list.get(i);

          List l = DbUtil.selectOne(Common.SELECT_STUDENT_SQL + "'%" + student.getName() + "%'", student);

          if (!l.contains(1)) {

              DbUtil.insert(Common.INSERT_STUDENT_SQL, student);

          } else {

              System.out.println("The Record was Exist : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + ", and has been throw away!");

          }

      }

  }

}

保存结果:

如何将excel表数据导入MySql数据库

一般有两种方式来处理

1、使用js来读取本地excel文件,读出一行后,使用ajax传入后台进行持久化操作(存入数据库),这种方式仅限于windows和ie,要使用

var oXL = new ActiveXObject("Excel.application");

var oWB = oXL.Workbooks.open(filePath);

oWB.worksheets(1).select();

var oSheet = oWB.ActiveSheet;

2、使用poi插件来处理,前台使用input type="file" value=""来加载本地excel文件,提交到后台后,使用流保存到服务器,在使用poi处理,保存进入数据库

从安全性和规范性、通用性考虑,第二种方法更为合适

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。