如何在Java中导入Excel表数据

如何在Java中导入Excel表数据,第1张

1,加入依赖的罐子文件:

引用:

*mysql的jar文件

*Spring_HOME/lib/poi/*.jar

2,编写数据库链接类

package com.zzg.db

import java.sql.Connection

import java.sql.DriverManager

public class DbUtils {

private static Connection conn

static {

try {

Class.forName("com.mysql.jdbc.Driver")

conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456")

} catch (Exception e) {

e.printStackTrace()

}

}

public static Connection getConn() {

return conn

}

public static void setConn(Connection conn) {

DbUtils.conn = conn

}

}

3,编写数据库 *** 作类

package com.zzg.db

import java.sql.Connection

import java.sql.PreparedStatement

import java.sql.SQLException

public class ExcuteData {

private PreparedStatement pstmt

public boolean ExcuData(String sql) {

Connection conn = DbUtils.getConn()

boolean flag=false

try {

pstmt = conn.prepareStatement(sql)

flag=pstmt.execute()

} catch (SQLException e) {

e.printStackTrace()

}

return flag

}

}

4,编写的Excel表格实体类

package com.zzg.model

public class TableCell {

private String _name

private String _value

public String get_name() {

return _name

}

public void set_name(String _name) {

this._name = _name

}

public String get_value() {

return _value

}

public void set_value(String _value) {

this._value = _value

}

}

5,编写主键生成方法

package com.zzg.util

import java.text.SimpleDateFormat

import java.util.Date

import java.util.Random

public class GenericUtil {

public static String getPrimaryKey()

{

String primaryKey

primaryKey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())

Random r = new Random()

primaryKey +=r.nextInt(100000)+100000

return primaryKey

}

}

6,编写的Excel *** 作类

package com.zzg.deployData

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.IOException

import java.io.Serializable

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.zzg.db.ExcuteData

import com.zzg.model.TableCell

import com.zzg.util.GenericUtil

public class OperExcel<T extends Serializable>{

private HSSFWorkbook workbook

private String tableName

private Class<T>type

private String sheetName

public OperExcel(File excelFile, String tableName, Class<T>type,

String sheetName) throws FileNotFoundException,

IOException {

workbook = new HSSFWorkbook(new FileInputStream(excelFile))

this.tableName = tableName

this.type = type

this.sheetName = sheetName

InsertData()

}

// 向表中写入数据

public void InsertData() {

System.out.println("yyy")

ExcuteData excuteData = new ExcuteData()

List<List>datas = getDatasInSheet(this.sheetName)

// 向表中添加数据之前先删除表中数据

String strSql = "delete from " + this.tableName

excuteData.ExcuData(strSql)

// 拼接sql语句

for (int i = 1i <datas.size()i++) {

strSql = "insert into " + this.tableName + "("

List row = datas.get(i)

for (short n = 0n <row.size()n++) {

TableCell excel = (TableCell) row.get(n)

if (n != row.size() - 1)

strSql += excel.get_name() + ","

else

strSql += excel.get_name() + ")"

}

strSql += " values ("

for (short n = 0n <row.size()n++) {

TableCell excel = (TableCell) row.get(n)

try {

if (n != row.size() - 1) {

strSql += getTypeChangeValue(excel) + ","

} else

strSql += getTypeChangeValue(excel) + ")"

} catch (RuntimeException e) {

e.printStackTrace()

} catch (Exception e) {

e.printStackTrace()

}

}

//执行sql

excuteData.ExcuData(strSql)

}

}

/**

* 获得表中的数据

* @param sheetName 表格索引(EXCEL 是多表文档,所以需要输入表索引号)

* @return 由LIST构成的行和表

*/

public List<List>getDatasInSheet(String sheetName) {

List<List>result = new ArrayList<List>()

// 获得指定的表

HSSFSheet sheet = workbook.getSheet(sheetName)

// 获得数据总行数

int rowCount = sheet.getLastRowNum()

if (rowCount <1) {

return result

}

// 逐行读取数据

for (int rowIndex = 0rowIndex <rowCountrowIndex++) {

// 获得行对象

HSSFRow row = sheet.getRow(rowIndex)

if (row != null) {

List<TableCell>rowData = new ArrayList<TableCell>()

// 获得本行中单元格的个数

int columnCount = sheet.getRow(0).getLastCellNum()

// 获得本行中各单元格中的数据

for (short columnIndex = 0columnIndex <columnCountcolumnIndex++) {

HSSFCell cell = row.getCell(columnIndex)

// 获得指定单元格中数据

Object cellStr = this.getCellString(cell)

TableCell TableCell = new TableCell()

TableCell.set_name(getCellString(

sheet.getRow(0).getCell(columnIndex)).toString())

TableCell.set_value(cellStr == null ? "" : cellStr

.toString())

rowData.add(TableCell)

}

result.add(rowData)

}

}

return result

}

/**

* 获得单元格中的内容

* @param cell

* @return result

*/

protected Object getCellString(HSSFCell cell) {

Object result = null

if (cell != null) {

int cellType = cell.getCellType()

switch (cellType) {

case HSSFCell.CELL_TYPE_STRING:

result = cell.getStringCellValue()

break

case HSSFCell.CELL_TYPE_NUMERIC:

result = cell.getNumericCellValue()

break

case HSSFCell.CELL_TYPE_FORMULA:

result = cell.getNumericCellValue()

break

case HSSFCell.CELL_TYPE_ERROR:

result = null

break

case HSSFCell.CELL_TYPE_BOOLEAN:

result = cell.getBooleanCellValue()

break

case HSSFCell.CELL_TYPE_BLANK:

result = null

break

}

}

return result

}

// 根据类型返回相应的值

@SuppressWarnings("unchecked")

public String getTypeChangeValue(TableCell excelElement)

throws RuntimeException, Exception {

String colName = excelElement.get_name()

String colValue = excelElement.get_value()

String retValue = ""

if (colName.equals("id")) {

retValue = "'" + GenericUtil.getPrimaryKey() + "'"

return retValue

}

if (colName == null) {

retValue = null

}

if (colName.equals("class_createuser")) {

retValue = "yaa101"

return "'" + retValue + "'"

}

retValue = "'" + colValue + "'"

return retValue

}

}

7,编写调用 *** 作的Excel类的方法

package com.zzg.deployData

import java.io.File

import java.io.FileNotFoundException

import java.io.IOException

public class DeployData {

private File fileOut

public void excute(String filepath) {

fileOut = new File(filepath)

this.deployUserInfoData()

}

public void deployUserInfoData() {

try {

new OperExcel(fileOut, "test", Object.class, "Sheet1")

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

}

8,编写客户端

package com.zzg.client

import com.zzg.deployData.DeployData

public class DeployClient {

public static void main(String[] args) {

DeployData deployData = new DeployData()

deployData.excute("D://test.xls")

}

}

public static void main(String args[]) throws BiffException, IOException, WriteException{

//1 从Excel文件读取数据表

//Java Excel API既可以从本地文件系统的一个文件(.xls),也可以从输入流中读取Excel数据表。

//读取Excel数据表的第一步是创建Workbook(术语:工作薄),下面的代码片段举例说明了应该如何 *** 作:

//(完整代码见ExcelReading.java)

try

{

//构建Workbook对象, 只读Workbook对象

//直接从本地文件创建Workbook

//从输入流创建Workbook

InputStream is = new FileInputStream("D:/user.xls")

jxl.Workbook rwb = Workbook.getWorkbook(is)

//一旦创建了Workbook,我们就可以通过它来访问Excel Sheet(术语:工作表)。参考下面的代码片段:

//获取第一张Sheet表

Sheet rs = (Sheet) rwb.getSheet(0)

//我们既可能通过Sheet的名称来访问它,也可以通过下标来访问它。如果通过下标来访问的话,

//要注意的一点是下标从0开始,就像数组一样。

//一旦得到了Sheet,我们就可以通过它来访问Excel Cell(术语:单元格)。参考下面的代码片段:

//获取第一行,第一列的值

Cell c00 = ((jxl.Sheet) rs).getCell(0, 0)

String strc00 = c00.getContents()

//获取第一行,第二列的值

Cell c10 = ((jxl.Sheet) rs).getCell(1, 0)

String strc10 = c10.getContents()

//获取第二行,第二列的值

Cell c11 = ((jxl.Sheet) rs).getCell(1, 1)

String strc11 = c11.getContents()

System.out.println("Cell(0, 0)" + " value : " + strc00 + "type : " + c00.getType())

System.out.println("Cell(1, 0)" + " value : " + strc10 + "type : " + c10.getType())

System.out.println("Cell(1, 1)" + " value : " + strc11 + "type : " + c11.getType())

//如果仅仅是取得Cell的值,我们可以方便地通过getContents()方法,

//它可以将任何类型的Cell值都作为一个字符串返回。示例代码中Cell(0, 0)是文本型,

//Cell(1, 0)是数字型,Cell(1,1)是日期型,通过getContents(),三种类型的返回值都是字符型。

//如果有需要知道Cell内容的确切类型,API也提供了一系列的方法。参考下面的代码片段:

String strcc00 = null

double strcc10 = 0.00

Date strcc11 = null

Cell cc00 = ((jxl.Sheet) rs).getCell(0, 0)

Cell cc10 = ((jxl.Sheet) rs).getCell(1, 0)

Cell cc11 = ((jxl.Sheet) rs).getCell(1, 1)

if(c00.getType() == CellType.LABEL)

{

LabelCell labelc00 = (LabelCell)cc00

strcc00 = labelc00.getString()

}

if(c10.getType() == CellType.NUMBER)

{

NumberCell numc10 = (NumberCell)cc10

strcc10 = numc10.getValue()

}

if(c11.getType() == CellType.DATE)

{

DateCell datec11 = (DateCell)cc11

strcc11 = datec11.getDate()

}

System.out.println("Cell(0, 0)" + " value : " + strcc00 + "type : " + cc00.getType())

System.out.println("Cell(1, 0)" + " value : " + strcc10 + "type : " + cc10.getType())

System.out.println("Cell(1, 1)" + " value : " + strcc11 + "type : " + cc11.getType())

//在得到Cell对象后,通过getType()方法可以获得该单元格的类型,然后与API提供的基本类型相匹配,

//强制转换成相应的类型,最后调用相应的取值方法getXXX(),就可以得到确定类型的值。

//API提供了以下基本类型,与Excel的数据格式相对应,如下图所示:

//每种类型的具体意义,请参见Java Excel API Document。

//当你完成对Excel电子表格数据的处理后,一定要使用close()方法来关闭先前创建的对象,

//以释放读取数据表的过程中所占用的内存空间,在读取大量数据时显得尤为重要。参考如下代码片段:

// *** 作完成时,关闭对象,释放占用的内存空间

rwb.close()

}

catch (Exception e)

{

e.printStackTrace()

}

//Java Excel API提供了许多访问Excel数据表的方法,在这里我只简要地介绍几个常用的方法,

//其它的方法请参考附录中的Java Excel API Document。

//Workbook类提供的方法

//1. int getNumberOfSheets()

//获得工作薄(Workbook)中工作表(Sheet)的个数,示例:

jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

int sheets = rwb.getNumberOfSheets()

//2. Sheet[] getSheets()

//返回工作薄(Workbook)中工作表(Sheet)对象数组,示例:

jxl.Workbook rwb2 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

Sheet[] sheets2 = (Sheet[]) rwb2.getSheets()

//3. String getVersion()

//返回正在使用的API的版本号,好像是没什么太大的作用。

jxl.Workbook rwb3 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

String apiVersion = rwb3.getVersion()

//Sheet接口提供的方法

//1) String getName()

//获取Sheet的名称,示例:

jxl.Workbook rwb4 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs = rwb4.getSheet(0)

String sheetName = rs.getName()

//2) int getColumns()

//获取Sheet表中所包含的总列数,示例:

jxl.Workbook rwb5 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs2 = rwb5.getSheet(0)

int rsColumns = rs2.getColumns()

//3) Cell[] getColumn(int column)

//获取某一列的所有单元格,返回的是单元格对象数组,示例:

jxl.Workbook rwb6 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs3 = rwb6.getSheet(0)

Cell[] cell = rs3.getColumn(0)

//4) int getRows()

//获取Sheet表中所包含的总行数,示例:

jxl.Workbook rwb7 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs4 = rwb7.getSheet(0)

int rsRows = rs4.getRows()

//5) Cell[] getRow(int row)

//获取某一行的所有单元格,返回的是单元格对象数组,示例子:

jxl.Workbook rwb8 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs5 = rwb8.getSheet(0)

Cell[] cell5 = rs5.getRow(0)

//6) Cell getCell(int column, int row)

//获取指定单元格的对象引用,需要注意的是它的两个参数,第一个是列数,第二个是行数,

//这与通常的行、列组合有些不同。

jxl.Workbook rwb9 = jxl.Workbook.getWorkbook(new File("D:/user.xls"))

jxl.Sheet rs6 = rwb9.getSheet(0)

Cell cell6 = rs6.getCell(0, 0)

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

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

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

具体如下:

1、简介

编程是编写程序的中文简称,就是让计算机代为解决某个问题,对某个计算体系规定一定的运算方式,是计算体系按照该计算方式运行,并最终得到相应结果的过程。

为了使计算机能够理解人的意图,人类就必须将需解决的问题的思路、方法和手段通过计算机能够理解的形式告诉计算机,使得计算机能够根据人的指令一步一步去工作,完成某种特定的任务。这种人和计算体系之间交流的过程就是编程。

2、汇编程序

汇编程序。使用汇编语言编写计算机程序,程序员仍然需要十分熟悉计算机系统的硬件结构,所以从程序设计本身上来看仍然是低效率的、繁琐的。但正是由于汇编语言与计算机硬件系统关系密切,在某些特定的场合,如对时空效率要求很高的系统核心程序以及实时控制程序等,迄今为止汇编语言仍然是十分有效的程序设计工具。

3、执行原理

计算机对除机器语言以外的源程序不能直接识别、理解和执行,都必须通过某种方式转换为计算机能够直接执行的。这种将高级编程硬件程序设计语言编写的源程序转换到机器目标程序的方式有两种:解释方式和编译方式。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/11941606.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存