您的位置:首页 > 编程语言 > Java开发

Java Excel表格数据解析封装

2014-07-04 00:00 561 查看
解析方法 java poi 对excel表格进行操作。

封装 Map 集合封装

Excel标题头解析步骤:

(标题头占用多行excel时)

1、 首先把表格标题头解析(以便确立这个表格的几何包含关系,方便后面数据封装);

2、 解析时从标题头的第一行开始,记录第一行的标题头中每个单元格的位置,放到一个Map型的ArrayList集合中;

1) 单元格位置记录





1、 接着开始解析第二行,解析第二行时先将第一行的每个单元格的位置遍历出来,然后解析第二行。

1) 解析第二行时,每个单元格的位置与遍历出的第一行的单元格的位置做比较,比较出第二行与第一行的位置关系之后,同时将他们放入Map集合。





2、 如果标题头有更多行,那么第二行每个单元格的位置也要记录到一个集合中,然后你解析当前行的时候,都要与上一行的位置做比较;

3、 解析完之后就确立的这个表格集合包含关系,这样这个表格的模板就确立了。

Excel 数据封装

1、 创建一个与上面我们解析出的模板相同的对象,然后将这个对象实例化,

2、 接着创建一个静态方法,





传入创建的对象,然后将对象中的Map嵌套集合,分层遍历

3、 接着将表格的数据封装到上面我们解析的模板中

1、 完整案例:

创建模板对象

import java.util.HashMap;

import java.util.Map;

public class Thiocyanate {

String name;

Map<String,Map<String,Map<String,String>>> type;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Map<String, Map<String, Map<String, String>>> getType() {

return type;

}

public void setType(Map<String, Map<String, Map<String, String>>> type) {

this.type = type;

}

public Thiocyanate(String name,Map<String,Map<String,Map<String,String>>> type){

this.name = name;

this.type = type;

}

public static Thiocyanate clone(Thiocyanate t){

Map<String, Map<String, Map<String, String>>> type0 = t.getType();

String name = t.getName();

Map<String, Map<String, Map<String, String>>> type = new HashMap<String, Map<String, Map<String, String>>>();

for(String tmp : type0.keySet()){

Map<String, Map<String, String>> tV = new HashMap<String, Map<String, String>>(type0.get(tmp));

type.put(tmp, tV);

for(String ttt :tV.keySet()){

Map<String,String> tmpValue = new HashMap<String,String>(tV.get(ttt));

tV.put(ttt, tmpValue);

}

}

return new Thiocyanate(name,type);

}

@Override

public String toString() {

if(this.type.get("抽检样品") != null)

this.type.remove("抽检样品");

return "Thiocyanate [name=" + name + ", type=" + type + "]";

}

}

2、 解析标题头以及数据的封装:

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.util.CellRangeAddress;

import cn.dviz.domain.Microorganism;

import cn.dviz.domain.Thiocyanate;

public class hssfThiocyanate {

Workbook xwb = null;

Sheet sheet = null;

Row rowObj = null;

Cell cell = null;

public void read(String strpath, boolean method) throws Exception {

System.out.println("parse start ……");

parseExcel2003(strpath);

System.out.println("parse end ……");

}

private void parseExcel2003(String strpath) throws Exception {

try {

InputStream file = new FileInputStream(strpath);

xwb = new HSSFWorkbook(new POIFSFileSystem(file));

} catch (FileNotFoundException e) {

e.printStackTrace();

}

//封装定义模板

Thiocyanate th=null;

int k=3;

sheet = xwb.getSheetAt(k);

int rowNum = sheet.getFirstRowNum();

ArrayList<Map<String, Integer[]>> position = new ArrayList<>();

rowNum = 1;

rowObj = sheet.getRow(rowNum);

if (rowObj != null) {

int cellNum = rowObj.getFirstCellNum() < 0 ? 0 : rowObj

.getFirstCellNum();

int cellTotalNum = rowObj.getPhysicalNumberOfCells();

for (; cellNum < cellTotalNum; cellNum++) {

cell = rowObj.getCell(cellNum);

CellRangeAddress ca = isMergedRegion(sheet, rowNum, cellNum);

if (ca != null) {

int FirstColumn = ca.getFirstColumn();

int LastColumn = ca.getLastColumn();

Integer[] posi = { FirstColumn, LastColumn };

Map<String, Integer[]> p = new HashMap<String, Integer[]>();

p.put(cell.getStringCellValue(), posi);

int s = position.size();

if ("".equals(cell.getStringCellValue()))

continue;

boolean flag = false;

for (int ii = 0; ii < s; ii++) {

Map<String, Integer[]> p0 = position.get(ii);

if (p0.get(cell.getStringCellValue()) != null) {

flag = true;

continue;

}

}

if (!flag)

position.add(p);

}

}

}

String fname = position.get(0).keySet().toArray()[0].toString();

Map<String, Map<String, Map<String, String>>> type = new HashMap<String, Map<String, Map<String, String>>>();

String typeName = position.get(1).keySet().toArray()[0].toString();

Map<String,Map<String,String>> typeValue=new HashMap<String,Map<String,String>>();

type.put(typeName, typeValue);

th=new Thiocyanate(fname, type);

rowNum = 2;

rowObj = sheet.getRow(rowNum);

String cellname = null;

Integer[] cellposi = null;

if (rowObj != null) {

int cellNum = rowObj.getFirstCellNum() < 0 ? 0 : rowObj

.getFirstCellNum();

int cellTotalNum = rowObj.getPhysicalNumberOfCells();

for (; cellNum < cellTotalNum; cellNum++) {

cell = rowObj.getCell(cellNum);

String cellValue = cell.getStringCellValue().replace("\n", " ");

for (int i = 2; i < position.size(); i++) {

Map<String, Integer[]> p = (Map<String, Integer[]>) position

.get(i);

for (Map.Entry<String, Integer[]> entry : p.entrySet()) {

cellname = entry.getKey();

cellposi = entry.getValue();

int firstColumn = cellposi[0];

int lastColumn = cellposi[1];

Map<String, String> t0 = new HashMap<String, String>();

if (typeValue.get(cellname) == null)

typeValue.put(cellname, t0);

else

t0 = typeValue.get(cellname);

if (cellNum >= firstColumn && cellNum <= lastColumn) {

String tmp = t0.get(cellValue);

if (tmp == null || !tmp.equals(cellNum)) {

t0.put(cellValue + cellNum, cellNum + "");

}

}

}

}

}

}

List<Thiocyanate> data = new ArrayList<Thiocyanate>();

String fnameD = "";

String ftypeD = "";

int rowTotalNum=16;

for (rowNum = 4; rowNum < rowTotalNum; rowNum++) {

rowObj = sheet.getRow(rowNum);

if (rowObj != null) {

int cellNum = rowObj.getFirstCellNum() < 0 ? 0 : rowObj.getFirstCellNum();

int cellTotalNum = rowObj.getPhysicalNumberOfCells();

Thiocyanate mData = Thiocyanate.clone(th);

try{

for (; cellNum < cellTotalNum; cellNum++) {

cell = rowObj.getCell(cellNum);

if(cellNum == 0 && cell.getCellType() != Cell.CELL_TYPE_BLANK)

fnameD = cell.getStringCellValue();

if(cellNum == 0 && cell.getCellType() != Cell.CELL_TYPE_STRING && "".equals(fnameD))

break;

if(cellNum == 1){

ftypeD = cell.getStringCellValue();

}

mData.setType(setValue(mData.getType(),cell,cellNum));

}

}catch(Exception e){

e.printStackTrace();

}

mData.setName(fnameD);

if("".equals(ftypeD))ftypeD = "合计";

mData.getType().put(ftypeD, mData.getType().get("抽检样品"));

if(!"".equals(fnameD))

data.add(mData);

}

}

System.out.println(data.size());

for(Thiocyanate t : data){

System.out.println(t);

}

}

//将数值放入之前封装好的模板中

public Map<String,Map<String,Map<String,String>>> setValue(Map<String,Map<String,Map<String,String>>> mDataType,Cell cell,int cellNum){

Map<String, Map<String, String>> mm = mDataType.get("抽检样品");

if(mm == null)return mDataType;

Set<String> keys = mm.keySet();

for(String key : keys){

Map<String, String> m = mm.get(key);

Set<String> tKey = m.keySet();

for(String k : tKey)

if((cellNum+"").equals(m.get(k))){

m.put(k, getCellValue(cell)+"");

}

}

return mDataType;

}

//单元格中的值有特殊符号进行转换

public static String getCellValue(Cell cell) {

String cellValue = "";

if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

cellValue = String.valueOf(cell.getNumericCellValue());

} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {

cellValue = String.valueOf(cell.getBooleanCellValue());

} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {

cellValue = cell.getStringCellValue();

} else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {

try {

cellValue = String.valueOf(cell.getStringCellValue());

} catch (IllegalStateException e) {

cellValue = String.format("%.1f",

cell.getNumericCellValue() * 100) + '%';

}

}

return cellValue;

}

//记录单元格的位置

public CellRangeAddress isMergedRegion(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) {

return ca;

}

}

}

return null;

}

public static void main(String[] args)throws Exception {

hssfThiocyanate xs = new hssfThiocyanate();

xs.read("E:\\2012年3月份酸奶各工厂卫生指标与风险监控指标汇总20120409.xls", false);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: