大概思路:
1.获取前台传递过来的FILE文件及需要解析的XML文件ID
XML 如下:
<?xml version="1.0" encoding="UTF-8" ?>
<excels>
<!-- 电力调度机构-->
<excel id="SCSERC-DLDUJG" class="excelTemplateReaderHorizontal">
<!-- 用来封装的class-->
<sheet name="本调度机构基本信息" pojo="com.bsi.pojo.PowerDispatchOffice">
<row>
<cell index="0" title="企业名称" property="enterpriseName"/>
<cell index="1" title="统一社会信用代码/组织机构代码" property="creditCode"/>
<cell index="2" title="企业所属行业类别" property="qysshyClass"/>
<cell index="3" title="企业类型" property="qyClass"/>
<cell index="4" title="企业所在区域" property="qyRegion"/>
<cell index="5" title="企业住所" property="qyResidence"/>
<cell index="6" title="注册资金" property="registeredCapital"/>
<cell index="7" title="注册日期" property="registerDate"/>
</row>
</sheet>
<sheet name="本调度机构法定代表人基本信息" pojo="com.bsi.pojo.PowerDispatchOffice">
<row>
<cell index="0" title="所在企业名称" property="nameOfEnterprise"/>
<cell index="1" title="统一社会信用代码/组织机构代码" property="creditCode"/>
<cell index="2" title="法定代表人姓名" property="legalRepresentativeName"/>
<cell index="3" title="企业类型" property="qyClass"/>
<cell index="4" title="个人证件类型" property="personalPapersType"/>
<cell index="5" title="个人证件号码" property="code"/>
<cell index="6" title="性别" property="sex"/>
</row>
</sheet>
<sheet name="市场主体不良行为信息" pojo="com.bsi.pojo.PowerDispatchOffice">
<row>
<cell index="0" title="企业名称" property="enterpriseName"/>
<cell index="1" title="统一社会信用代码/组织机构代码" property="creditCode"/>
<cell index="2" title="不良行为分类" property="blxwClass"/>
<cell index="3" title="不良行为描述" property="blxwDescribe"/>
<cell index="4" title="处理措施" property="handleStep"/>
<cell index="5" title="处理依据" property="handleBasis"/>
<cell index="6" title="处理日期" property="handleDate"/>
<cell index="7" title="处理单位" property="handleOffice"/>
</row>
</sheet>
</excel>
</excels>
2. 将其XML id 和FILE 文件传递给ExcelTemplateDefine 模板 去解析XML
// 根据ID,取得对应的解析模板
Element e = ExcelReader.getInstance().getTreeElement(id);
parseExcel(id,e, file);
3. 调用parseExcel方法去解析EXCEL
大致代码如下:
/**导入处理
* @throws Exception */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void importExcel() throws Exception {
excelTemplateDefine.execute(importFileType, importFile);
Map<String, List> dataMap = excelTemplateDefine.getParseDate();
Iterator<Entry<String,List>> it = dataMap.entrySet().iterator();
String success = "";
while (it.hasNext())
{
Entry<String, List> entry = (Entry<String, List>)it.next();
List list = entry.getValue();
for(int i=0;i<list.size();i++){
Object object = excelEnterpriseService.saveAEnterprise(importFileType,list.get(i));
if(!object.equals("1")){
success += entry.getKey()+">>>>>"+ object ;
}
}
}
if(StringUtils.isNotBlank(success)){
JsonUtils.outputString(success, getResponse());
}else{
JsonUtils.outputString("数据导入成功!", getResponse());
}
}
excelTemplateDefine.execute(importFileType, importFile);
方法如下:
package com.bsi.excel.parse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.bsi.excel.exception.ExcelException;
import com.bsi.util.SpringUtil;
import com.bsi.util.StringUtils;
/**
* 解析XML数据
*
* 根据传进去的模板,自动解析数据,并返回
*/
@Component("excelTemplateDefine")
@Scope("prototype")
public class ExcelTemplateDefine {
@SuppressWarnings("rawtypes")
private Map<String, List> parseDate;
private List<ExcelException> businessExceptionList;
@SuppressWarnings("rawtypes")
public void execute(String id, File file) throws Exception {
// init
parseDate = new HashMap<String, List>();
businessExceptionList = new ArrayList<ExcelException>();
// 根据ID,取得对应的解析模板
Element e = ExcelReader.getInstance().getTreeElement(id);
parseExcel(id,e, file);
}
@SuppressWarnings("rawtypes")
public void parseExcel(String idMoBan,Element e, File file) throws Exception {
Workbook workbook = new HSSFWorkbook(new FileInputStream(file));
List<Sheet> lists = getSheets(workbook);
for (Sheet sheet : lists) {
// 取得对应的service
if(e==null){continue;}
IExcelTemplateReader searvice = getService(e.attributeValue("class"));
System.out.println("开始解析sheet:" + sheet.getSheetName());
try {
Element sheetElement = getSheetElement(idMoBan,sheet.getSheetName(), e);
// 如果sheet是空的
if (sheetElement != null && sheetElement.attribute("noRead") == null) {
// 取得解析数据
List list = searvice.parseSheet(sheet, sheetElement);
// 进行验证
// doValidate(sheetElement, list);
parseDate.put(sheet.getSheetName(), list);
}
} catch (Exception a) {
System.out.println(file.getAbsolutePath());
if (a instanceof ExcelException) {
ExcelException ec = (ExcelException) a;
ec.setPosition(ec.getPosition() + "," + sheet.getSheetName() + "工作薄");
}
throw a;
}
}
}
// 多线程导入
@SuppressWarnings({ "rawtypes", "unchecked" })
public void doValidate(Element sheetElement, List list) throws Exception {
if (businessExceptionList == null) {
businessExceptionList = new ArrayList<ExcelException>();
}
Element element = sheetElement.element("validates");
if (element != null) {
List<Element> validateList = element.elements("validate");
if (validateList != null && !validateList.isEmpty()) {
for (Element validateE : validateList) {
String validateClassName = validateE.attributeValue("class");
if (StringUtils.isBlank(validateClassName)) {
validateClassName = "excelTemplaterHorizontalValidate";
}
// 屏蔽验证
ExcelValidate excelValidate = (ExcelValidate) SpringUtil.getBean(validateClassName);
String pojoName = sheetElement.attributeValue("pojo");
excelValidate.execute(list, validateE, Class.forName(pojoName)); // 取得业务规则的异常
businessExceptionList.addAll(excelValidate.getExcelExceptionList());
}
}
}
}
private IExcelTemplateReader getService(String className) throws Exception {
IExcelTemplateReader searvice = (IExcelTemplateReader) SpringUtil.getBean(className);
return searvice;
}
// 取得所有sheet
public List<Sheet> getSheets(Workbook workbook) {
if (null != workbook) {
int sheetNum = workbook.getNumberOfSheets();
List<Sheet> sheets = new ArrayList<Sheet>();
for (int i = 0; i < sheetNum; i++) {
sheets.add(workbook.getSheetAt(i));
}
return sheets;
}
return null;
}
// 根据sheet名称,取得解析的格式
@SuppressWarnings("unchecked")
public Element getSheetElement(String moBanId,String name, Element e ) throws Exception {
Element sheetElement = null;
// 默认的解析格式,没有sheet的名称
Element defaultElement = null;
List<Element> list = e.elements("sheet");
if (list != null && !list.isEmpty()) {
for (Element subElement : list) {
Attribute attribute = subElement.attribute("name");
if (attribute != null) {
if (name.equalsIgnoreCase(attribute.getValue())) {
sheetElement = subElement;
break;
}else if(StringUtils.isNotBlank(moBanId)&&moBanId.equals(attribute.getValue())){
sheetElement = subElement;
break;
}
} else {// 取得默认的解析格式
defaultElement = subElement;
}
}
}
// 根据sheet名称,没有找到对应的解析格式,则取默认的计解析格式
if (sheetElement == null) {
sheetElement = defaultElement;
}
return sheetElement;
}
@SuppressWarnings("rawtypes")
public Map<String, List> getParseDate() {
return parseDate;
}
@SuppressWarnings("rawtypes")
public void setParseDate(Map<String, List> parseDate) {
this.parseDate = parseDate;
}
public List<ExcelException> getBusinessExceptionList() {
return businessExceptionList;
}
public void setBusinessExceptionList(List<ExcelException> businessExceptionList) {
this.businessExceptionList = businessExceptionList;
}
}
解析模板类:
/**
* 单例模式,读取整个excel
*
*/
public class ExcelReader {
private static ExcelReader instance;
private File file;
private ExcelReader() {
file = new File(FileUtil.getWebContentPath() + "exceltemplate");
}
public synchronized static ExcelReader getInstance() {
if (instance == null) {
instance = new ExcelReader();
}
return instance;
}
// 取得excel解析模板
@SuppressWarnings("unchecked")
public Element getTreeElement(String name) throws Exception {
if (file.exists() && file.isDirectory()) {
for (File inputXml : file.listFiles()) {//获取项目中 exceltemplate文件夹下的所有的XML
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
Element employees = document.getRootElement();
List<Element> list = employees.elements();
for (Element employee : list) {
if (name.equals(employee.attribute("id").getValue())) {
System.out.println(inputXml.getAbsoluteFile());
return employee;
}
}
}
}
return null;
}
}
public class ExcelTemplateReaderHorizontal extends IExcelTemplateReader {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List parseSheet(Sheet sheet, Element sheetElement) throws Exception {
this.sheet = sheet;
String pojoName = sheetElement.attributeValue("pojo");
// 初始化变量
List resultList = new ArrayList();
int rowNum = sheet.getPhysicalNumberOfRows();
if (rowNum > 0) {
rowElement = sheetElement.element("row");
List<Element> list = rowElement.elements("cell");
String subjectClass = sheet.getRow(0).getCell(0).getStringCellValue();
String infoClass = sheet.getRow(1).getCell(0).getStringCellValue();
String infoClassName = sheet.getRow(2).getCell(0).getStringCellValue();
for (x = 4; x < rowNum; x++) {
Row row = sheet.getRow(x);
if (row == null) {
continue;
}
try {
Object object = fillObject(subjectClass,infoClass,infoClassName,list, row, pojoName);
if (object != null)
resultList.add(object);
} catch (ExcelException e) {
e.setPosition("第" + (++x) + "行," + "第" + (++y) + "列");
throw e;
} catch (Exception e1) {
e1.printStackTrace();
ExcelException e = new ExcelException();
e.setMsg("数据格式不对!");
e.setPosition("第" + (++x) + "行," + "第" + (++y) + "列");
throw e;
}
/*if (cell_first != null) {
}else{//cell_first == null
Object object = fillObject(list, row, pojoName);
if (object != null){resultList.add(object);}
}*/
}
}
return resultList;
}
/**
* 默认:
* 1、指定导入行范围first last或者first lastKey
* 2、指定导入行 range
* 3、如果第一个cell为数字,则表示该条记录为可以用记录sequence
* 4、根据cell的值来导入
* **/
private boolean canParse(Element rowElement, Cell cell_first) {
return canParseForNotNull(rowElement, cell_first)
|| canParseForNum(rowElement, cell_first)
|| canParseForFirst(rowElement, cell_first)
|| canParseFoRrange(rowElement, cell_first);
}
private boolean canParseForNotNull(Element rowElement, Cell cell_first) {
Attribute cellValueRanger = rowElement.attribute("cellValueRanger");
if (cellValueRanger != null) {
return true;
}
return false;
}
private boolean canParseForNum(Element rowElement, Cell cell_first) {
Attribute attributeSequence = rowElement.attribute("sequence");
if (attributeSequence != null) {
String firsCelltValue = getMulCellValue(cell_first);
/*// 如果第一个cell为数字,则表示该条记录为可以用记录
return StringUtils.isNumeric(firsCelltValue);*/
return true;
}
return false;
}
private boolean canParseForFirst(Element rowElement, Cell cell_first) {
Attribute attribute = rowElement.attribute("first");
if (attribute != null) {
int first = Integer.parseInt(rowElement.attributeValue("first"));
if (first > x) {
return false;
}
Attribute attributeLast = rowElement.attribute("last");
if (attributeLast != null) {
int last = Integer.parseInt(attributeLast.getValue());
if (last >= x) {
return true;
}
}
attributeLast = rowElement.attribute("lastKey");
if (attributeLast != null) {
String firsCelltValue = getMulCellValue(cell_first);
String[] attributeValArray = attributeLast.getValue().split(",");
for (String str : attributeValArray) {
if ("".equals(str)) {
if (StringUtils.isBlank(firsCelltValue)) {
return false;
}
} else if (firsCelltValue.indexOf(str) >= 0) {
return false;
}
}
return true;
}
}
return false;
}
private boolean canParseFoRrange(Element rowElement, Cell cell_first) {
Attribute attributeRange = rowElement.attribute("range");
if (attributeRange != null) {
String ranges = attributeRange.getValue();
String[] array = ranges.split(",");
Set<String> strSet = new HashSet<String>(Arrays.asList(array));
if (strSet.contains(Integer.toString(x))) {
return true;
}
}
return false;
}
// 取得一行数据
private Object fillObject(String subjectClass,String infoClass,String infoClassName,List<Element> list, Row row, String pojoName) throws Exception {
if (StringUtils.isNotBlank(pojoName)) {
return fillObjectForModel( subjectClass, infoClass, infoClassName,list, row, pojoName);
} else {
return fillObjectForArray(list, row);
}
}
// 将一行的数据,转换成对象
private Object fillObjectForModel(String subjectClass,String infoClass,String infoClassName,List<Element> list, Row row, String pojoName) throws Exception {
Object obj = Class.forName(pojoName).newInstance();
// 判断是否根据cellValue来过滤
if (!cellValueRange(row)) {
return null;
}
String remark = "";
for (Element e : list) {
// cell的序号
y = Integer.parseInt(e.attributeValue("index"));
// 增加去重属性
Attribute keArribute = e.attribute("key");
// pojo对应属性名
String property = e.attributeValue("property");
Cell cell = row.getCell(y);
String cellVal =null;
if(y==0){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,请填写数据!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}
if(property.equals("creditCode")){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,请填写数据!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}else{
cellVal= getMulCellValue(cell);
Pattern p = Pattern.compile("//[^_IOZSVa-z\\W]{2}\\d{6}[^_IOZSVa-z\\W]{10}//g");
Matcher matcher = p.matcher(cellVal);
Pattern pattern = Pattern.compile("//^([0-9A-Z]){8}-[0-9|X]$//");
Matcher matchers = pattern.matcher(cellVal);
if(matcher.matches()==true||matchers.matches()==true){
// 增加对特殊行的处理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 转换cell的值
Object converterResult = converterVal(e, cellVal);
// 将值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
continue;
}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,数据格式错误!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}
}
if(property.equals("code")){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,请填写数据!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}else{
cellVal= getMulCellValue(cell);
Pattern p = Pattern.compile("^\\d{15}$|^\\d{17}[0-9Xx]$");
Matcher matcher = p.matcher(cellVal);
if(matcher.matches()==true){
// 增加对特殊行的处理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 转换cell的值
Object converterResult = converterVal(e, cellVal);
// 将值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
continue;
}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,数据格式错误!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}
}
if(property.length()>4){
String date = property.substring(property.length()-4,property.length());
if (cell == null) {
if(date.equals("Date")||date.equals("date")){
System.out.println(" property = " + property);
BeanMapper.setPropertyValue(obj, property, null);
continue;
}else{
System.out.println(" property = " + property);
BeanMapper.setPropertyValue(obj, property, "");
continue;
}
}
if(date.equals("Date")||date.equals("date")){
if(cell.getDateCellValue() instanceof Date){
BeanMapper.setPropertyValue(obj, property, cell.getDateCellValue());
}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,请填写正确的日期 如:1997/7/8!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}else{
cellVal= getMulCellValue(cell);
// 增加对特殊行的处理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 转换cell的值
Object converterResult = converterVal(e, cellVal);
// 将值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
}
}else{
cellVal= getMulCellValue(cell);
// 增加对特殊行的处理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 转换cell的值
Object converterResult = converterVal(e, cellVal);
// 将值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
}
}
BeanMapper.setPropertyValue(obj, "subjectClass", subjectClass);
BeanMapper.setPropertyValue(obj, "infoClass", infoClass);
BeanMapper.setPropertyValue(obj, "infoClassName", infoClassName);
return obj;
}
// 如果是特殊的列,则自定义处理方法
protected boolean isSpeciaRow(String cellVal, Row row, Object obj) {
return false;
}
// 根据cell值来确定范围
private boolean cellValueRange(Row row) {
Attribute cellValueRanger = rowElement.attribute("cellValueRanger");
if (cellValueRanger == null) {
return true;
}
String cellValueCnRanger = rowElement.attributeValue("cellValueCnRanger");
int cellValueIndexRanger = Integer.parseInt(rowElement.attributeValue("cellValueIndexRanger"));
Cell cell = row.getCell(cellValueIndexRanger);
String cellValue = getMulCellValue(cell);
Set<String> set = new HashSet<String>(Arrays.asList(cellValueCnRanger.split(",")));
if (set.contains(cellValue.trim())) {
return true;
}
return false;
}
// 将一行的数据,转换成数组
private Object fillObjectForArray(List<Element> list, Row row) throws Exception {
Object[] objectArray = new Object[list.size()];
int i = 0;
for (Element e : list) {
// cell的序号
int index = Integer.parseInt(e.attributeValue("index"));
// pojo对应属性名
Cell cell = row.getCell(index);
String cellValue = null;
// 是否合并单元格
boolean isMerge = isMergedRegion(sheet, x, y);
if (isMerge) {
cellValue = getMergedRegionValue(sheet, row.getRowNum(), y);
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue();
}
// 转换cell的值
Object converterResult = converterVal(e, cellValue);
// 将值放入数组中
objectArray[i] = converterResult;
i++;
}
return objectArray;
}
}
/**
* 解析excel的接口
*
*/
public abstract class IExcelTemplateReader {
protected int x;
protected int y;
protected Sheet sheet;
protected Set<String> keySet = new HashSet<String>();
// 模板相关对象
protected Element rowElement;
protected ConverterFunctionProvider provider;
/**
* 解析Excel。返回结果 1、List<Pojo> 2、List<Object[]>
*
* @param sheet
* @param sheetElement
* @return
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public abstract List parseSheet(Sheet sheet, Element sheetElement) throws Exception;
// 将Excel中值,转换成指定格式
// 转换分2种,
// 1、简易转换,直接调用静态类
// 2、复杂转换,实现转换接口
@SuppressWarnings("unchecked")
public Object converterVal(Element e, String cellValue) throws Exception {
Attribute converterAttribute = e.attribute("converter");
// 简单转换
if (converterAttribute != null) {
return CallStaticClass.runMenthodByClassMedthod(converterAttribute.getStringValue(), new Object[] { cellValue });
}
// 复杂转换
Element converterFunctionElement = e.element("converterFunction");
if (converterFunctionElement != null) {
String className = "";
Map<String, String> argMap = new HashMap<String, String>();
List<Element> argList = converterFunctionElement.elements("arg");
for (Element argElement : argList) {
String name = argElement.attributeValue("name");
String text = argElement.getStringValue();
if ("class.name".equalsIgnoreCase(name)) {
className = text;
} else {
argMap.put(name, text);
}
}
if (provider == null)
provider = (ConverterFunctionProvider) SpringUtil.getBean(className);
return provider.execute(argMap, cellValue);
}
// 没有任何转换,直接返回
return cellValue;
}
/**
* 判断指定的单元格是否是合并单元格
* @param sheet
* @param row 行下标
* @param column 列下标
* @return
*/
public boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}
/**
* 获取合并单元格的值
* @param sheet
* @param row
* @param column
* @return
*/
public String getMergedRegionValue(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell);
}
}
}
return null;
}
/**
* 获取单元格的值 ,供外提供调用
* @param cell
* @return
*/
public String getMulCellValue(Cell cell) {
String cellValue = null;
// 是否合并单元格
boolean isMerge = isMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
if (isMerge) {
cellValue = getMergedRegionValue(sheet, cell.getRowIndex(), cell.getColumnIndex());
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue();
}
return cellValue;
}
/**
* 获取单元格的值,不对外提供
* @param cell
* @return
*/
private String getCellValue(Cell cell) {
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return cell.getCellFormula();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
}
return "";
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public Element getRowElement() {
return rowElement;
}
public void setRowElement(Element rowElement) {
this.rowElement = rowElement;
}
public Set<String> getKeySet() {
return keySet;
}
public void setKeySet(Set<String> keySet) {
this.keySet = keySet;
}
}
BeanMapper.setPropertyValue(obj, "subjectClass", subjectClass);
方法:
public static Object setPropertyValue(Object target, String methodPre, Object val) throws Exception {
Method method2[] = target.getClass().getMethods();
for (int j = 0; j < method2.length; j++) {
String methodName2 = method2[j].getName();
if (methodName2.equalsIgnoreCase("set" + methodPre)) {
method2[j].invoke(target, new Object[] { val });
}
}
return target;
}
EXCEL模型样式: