java导入excel?java excel导入上千条数据需要3-5个线程。支持流处理,在生成大数据量的电子表格且堆空间有限时使用。SXSSF通过限制内存中可访问的记录行数来实现其低内存利用,当达到限定值时,那么,java导入excel?一起来了解一下吧。
1、加入依赖的jar文件:
引用:*mysql的jar文件
*Spring_HOME/lib/poi/*.jar
2、编写数据库链接类
packagecom.zzg.db;importjava.sql.Connection;
importjava.sql.DriverManager;
publicclassDbUtils{
privatestaticConnectionconn;
static{
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticConnectiongetConn(){
returnconn;
}
publicstaticvoidsetConn(Connectionconn){
DbUtils.conn=conn;
}
}
3、编写数据库操作类
packagecom.zzg.db;importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
咐蚂
publicclassExcuteData{
privatePreparedStatementpstmt;
publicbooleanExcuData(Stringsql){
Connectionconn=DbUtils.getConn();
booleanflag=false;
歼简梁try{
pstmt=conn.prepareStatement(sql);
flag=pstmt.execute();
}catch(SQLExceptione){
e.printStackTrace();
}
returnflag;
}
}
4、编写Excel表格实体类
packagecom.zzg.model;publicclassTableCell{
privateString_name;
privateString_value;
publicStringget_name(){
return_name;
}
publicvoidset_name(String_name){
this._name=_name;
}
publicStringget_value(){
return_value;
}
publicvoidset_value(String_value){
this._value=_value;
}
}
5、编写主键生成方法
packagecom.zzg.util;importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Random;氏运
publicclassGenericUtil{
publicstaticStringgetPrimaryKey()
{
StringprimaryKey;
primaryKey=newSimpleDateFormat("yyyyMMddHHmmss").format(newDate());
Randomr=newRandom();
primaryKey+=r.nextInt(100000)+100000;
returnprimaryKey;
}
}
6、编写Excel操作类
packagecom.zzg.deployData;importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.Serializable;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importcom.zzg.db.ExcuteData;
importcom.zzg.model.TableCell;
importcom.zzg.util.GenericUtil;
publicclassOperExcel
{ privateHSSFWorkbookworkbook;
privateStringtableName;
privateClass
type; privateStringsheetName;
publicOperExcel(FileexcelFile,StringtableName,Class
type, StringsheetName)throwsFileNotFoundException,
IOException{
workbook=newHSSFWorkbook(newFileInputStream(excelFile));
this.tableName=tableName;
this.type=type;
this.sheetName=sheetName;
InsertData();
}
//向表中写入数据
publicvoidInsertData(){
System.out.println("yyy");
ExcuteDataexcuteData=newExcuteData();
List
datas=getDatasInSheet(this.sheetName);
//向表中添加数据之前先删除表中数据
StringstrSql="deletefrom"+this.tableName;
excuteData.ExcuData(strSql);
//拼接sql语句
for(inti=1;i
strSql="insertinto"+this.tableName+"(";
Listrow=datas.get(i);
for(shortn=0;n
TableCellexcel=(TableCell)row.get(n);
if(n!=row.size()-1)
strSql+=excel.get_name()+",";
else
strSql+=excel.get_name()+")";
}
strSql+="values(";
for(shortn=0;n
TableCellexcel=(TableCell)row.get(n);
try{
if(n!=row.size()-1){
strSql+=getTypeChangeValue(excel)+",";
}else
strSql+=getTypeChangeValue(excel)+")";
}catch(RuntimeExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
//执行sql
excuteData.ExcuData(strSql);
}
}
/**
*获得表中的数据
*@paramsheetName表格索引(EXCEL是多表文档,所以需要输入表索引号)
*@return由LIST构成的行和表
*/
publicList
getDatasInSheet(StringsheetName){
List
result=newArrayList
();
//获得指定的表
HSSFSheetsheet=workbook.getSheet(sheetName);
//获得数据总行数
introwCount=sheet.getLastRowNum();
if(rowCount<1){
returnresult;
}
//逐行读取数据
for(introwIndex=0;rowIndex
//获得行对象
HSSFRowrow=sheet.getRow(rowIndex);
if(row!=null){
List
rowData=newArrayList (); //获得本行中单元格的个数
intcolumnCount=sheet.getRow(0).getLastCellNum();
//获得本行中各单元格中的数据
for(shortcolumnIndex=0;columnIndex
HSSFCellcell=row.getCell(columnIndex);
//获得指定单元格中数据
ObjectcellStr=this.getCellString(cell);
TableCellTableCell=newTableCell();
TableCell.set_name(getCellString(
sheet.getRow(0).getCell(columnIndex)).toString());
TableCell.set_value(cellStr==null?"":cellStr
.toString());
rowData.add(TableCell);
}
result.add(rowData);
}
}
returnresult;
}
/**
*获得单元格中的内容
*
*@paramcell
*@returnresult
*/
protectedObjectgetCellString(HSSFCellcell){
Objectresult=null;
if(cell!=null){
intcellType=cell.getCellType();
switch(cellType){
caseHSSFCell.CELL_TYPE_STRING:
result=cell.getStringCellValue();
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
result=cell.getNumericCellValue();
break;
caseHSSFCell.CELL_TYPE_FORMULA:
result=cell.getNumericCellValue();
break;
caseHSSFCell.CELL_TYPE_ERROR:
result=null;
break;
caseHSSFCell.CELL_TYPE_BOOLEAN:
result=cell.getBooleanCellValue();
break;
caseHSSFCell.CELL_TYPE_BLANK:
result=null;
break;
}
}
returnresult;
}
//根据类型返回相应的值
@SuppressWarnings("unchecked")
publicStringgetTypeChangeValue(TableCellexcelElement)
throwsRuntimeException,Exception{
StringcolName=excelElement.get_name();
StringcolValue=excelElement.get_value();
StringretValue="";
if(colName.equals("id")){
retValue="'"+GenericUtil.getPrimaryKey()+"'";
returnretValue;
}
if(colName==null){
retValue=null;
}
if(colName.equals("class_createuser")){
retValue="yaa101";
return"'"+retValue+"'";
}
retValue="'"+colValue+"'";
returnretValue;
}
}
7、编写调用操作Excel类的方法
packagecom.zzg.deployData;importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.IOException;
publicclassDeployData{
privateFilefileOut;
publicvoidexcute(Stringfilepath){
fileOut=newFile(filepath);
this.deployUserInfoData();
}
publicvoiddeployUserInfoData(){
try{
newOperExcel(fileOut,"test",Object.class,"Sheet1");
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
8、编写客户端
packagecom.zzg.client;importcom.zzg.deployData.DeployData;
publicclassDeployClient{
publicstaticvoidmain(String[]args){
DeployDatadeployData=newDeployData();
deployData.excute("D://test.xls");
}
}
这个问题分两步走:
利用Excel第扮改陆三方,将Excel文件读取到内存中。使用最简单,方便的是apache的poi包,自己网上http://poi.apache.org/ ,使用方法网上一搜一大片。
如果是对于特别大的excel(大于20M的话),简单的读取方法就容易内存溢出了,需要采用流式读取的方歼尘式,参考http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
将已读入内存的Excel数据厅顷,整理成写数据库的数据结构,然后插入数据库。这部分工作应该不用介绍了,就是基本的数据库操作方法,与excel无关了
File file = null; //写入file
Workbook book = null;
WritableWorkbook wbook = null; //写入wbook
File f = null;// 读取 f
file = new java.io.File(readPath);
book = Workbook.getWorkbook(file);
wbook = Workbook.createWorkbook(file, book);
WritableSheet sh = wbook.getSheet(0);// 写入数据 sheet
Sheet sheet = book.getSheet(0);
int length = sheet.getRows(); //得到当伏返前行缺睁饥早档数
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public static ArrayList
try {
//查询文件是否存在
File file = new File(filepath);
if (file.exists()) {
ArrayList
//声明一个excel文件对象
Workbook wb = Workbook.getWorkbook(file);
//读取汪旁缓每一个工作薄,你也可能用wb.getSheets()得到全部工作薄
Sheet ws = wb.getSheet(0);
if (null != ws) {
//取出所启庆有行
int rows = ws.getRows();
for (int i = 0; i < rows; i++) {
//读取第一列中的内容
String cell = ws.getCell(0, i).getContents();
if (null != cell) {
result.add(cell.trim());
}
}
}
return result;
}
return null;
} catch (BiffException e) {
e.printStackTrace();
return null;
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
List
以上就是java导入excel的全部内容,需要导入jxl.jar 搭建环境 将后的文件解包,得到jxl.jar,放入classpath,安装就完成了。创建文件 拟生成一个名为“测试数据.xls”的Excel文件,其中第一个工作表被命名为“第一页”。