当前位置: 首页 > 常见问题 > Excel表格

java导入excel,java读写Excel文件

  • Excel表格
  • 2023-08-15

java导入excel?java excel导入上千条数据需要3-5个线程。支持流处理,在生成大数据量的电子表格且堆空间有限时使用。SXSSF通过限制内存中可访问的记录行数来实现其低内存利用,当达到限定值时,那么,java导入excel?一起来了解一下吧。

java导出文件

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;

privateClasstype;

privateStringsheetName;

publicOperExcel(FileexcelFile,StringtableName,Classtype,

StringsheetName)throwsFileNotFoundException,

IOException{

workbook=newHSSFWorkbook(newFileInputStream(excelFile));

this.tableName=tableName;

this.type=type;

this.sheetName=sheetName;

InsertData();

}

//向表中写入数据

publicvoidInsertData(){

System.out.println("yyy");

ExcuteDataexcuteData=newExcuteData();

Listdatas=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构成的行和表

*/

publicListgetDatasInSheet(StringsheetName){

Listresult=newArrayList();

//获得指定的表

HSSFSheetsheet=workbook.getSheet(sheetName);

//获得数据总行数

introwCount=sheet.getLastRowNum();

if(rowCount<1){

returnresult;

}

//逐行读取数据

for(introwIndex=0;rowIndex

//获得行对象

HSSFRowrow=sheet.getRow(rowIndex);

if(row!=null){

ListrowData=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");

}

}

java excel

这个问题分两步走:

利用Excel第扮改陆三方,将Excel文件读取到内存中。使用最简单,方便的是apache的poi包,自己网上http://poi.apache.org/ ,使用方法网上一搜一大片。

如果是对于特别大的excel(大于20M的话),简单的读取方法就容易内存溢出了,需要采用流式读取的方歼尘式,参考http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api

将已读入内存的Excel数据厅顷,整理成写数据库的数据结构,然后插入数据库。这部分工作应该不用介绍了,就是基本的数据库操作方法,与excel无关了

java实现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(); //得到当伏返前行缺睁饥早档数

java读取excel文件

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 readTelExcel(String filepath) {

try {

//查询文件是否存在

File file = new File(filepath);

if (file.exists()) {

ArrayList result = new ArrayList<困模String>();

//声明一个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;

}

}

java怎么导入excel

List listPd2 = (List)ObjectExcelRead.readExcel(filePath, fileName, 1, 0, 1);//执行读EXCEL操作,读出的数据导入List 1:从第2行开始;0:从第慧神指1列前配开瞎尺始;1:第2个sheet 可以将多张表格放在同一张表格中用sheet1、sheet2来区分

以上就是java导入excel的全部内容,需要导入jxl.jar 搭建环境 将后的文件解包,得到jxl.jar,放入classpath,安装就完成了。创建文件 拟生成一个名为“测试数据.xls”的Excel文件,其中第一个工作表被命名为“第一页”。

猜你喜欢