导入Excel数据(语言:groovy)

import java.io.FileInputStream
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row


/**
* @author cdh
*
* 基于apache POI项目的实现
*/
public class Excels{
static getDateFromExcel(){
def workBook = getExcelWorkbook(new FileInputStream('D:/SaleMobile.xlsx'))
getSheetListByWorkbook(workBook).each {sheet ->
def rowList = Excels.getRowListBySheet(sheet)
def colCount = Excels.getFirstRowCellCount(sheet)//列数
rowList.remove(0.intValue())//去除第一行(文字行)
rowList.each {row->
def oVal = []
def cellList = Excels.getCellListByRow(row, colCount)
cellList.each {cell->
oVal << Excels.getValueByCell(cell)
}
}
}
}
/**
* inp FileInputStream
*/
static def getExcelWorkbook(inp) {
def wb = WorkbookFactory.create(inp);
wb.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK)
return wb
}

static def getSheetListByWorkbook(workbook) {
def sheetList = []
def i = 0
while (true) {
try {
def sheet = workbook.getSheetAt(i++)
sheetList << sheet
} catch (Exception e) {
return sheetList
}
}
}

static def getRowListBySheet(sheet) {
return sheet.rowIterator().collect{return it}
}

static def getFirstRowCellCount(sheet) {
return sheet.getRow(0).cellIterator().collect{return it}.@size
}

static def getCellListByRow(row, cellNum) {
--cellNum
def cellList = []
(0..cellNum).each {index->
cellList << row.getCell(index)
}
return cellList
}

static def getValueByCell(cell) {
if (cell.cellType == Cell.CELL_TYPE_BLANK) {
return ""
} else if (cell.cellType == Cell.CELL_TYPE_BOOLEAN) {
return cell.booleanCellValue
} else if (cell.cellType == Cell.CELL_TYPE_ERROR) {
return cell.errorCellValue
} else if (cell.cellType == Cell.CELL_TYPE_FORMULA) {
return cell.cellFormula
} else if (cell.cellType == Cell.CELL_TYPE_NUMERIC) {
return cell.numericCellValue
} else if (cell.cellType == Cell.CELL_TYPE_STRING) {
return cell.stringCellValue
} else {
return cell.stringCellValue
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值