package test.excel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.poi.ss.util.Region;
/**
* 吧list轉化成excel
* @author xsq QQ:624400382
*
*/
public abstract class ListToCombineExcel extends ListToTree{
private Map<String,HSSFRow> rowCache=new HashMap<String, HSSFRow>();
private Map<String,HSSFCell> cellCache=new HashMap<String, HSSFCell>();
private HSSFWorkbook workbook;
private HSSFSheet sheet;
private List<Node> treeNodes=null;
public ListToCombineExcel(HSSFWorkbook workbook, HSSFSheet sheet)
{
this.workbook=workbook;
this.sheet=sheet;
}
/**
* 這裡創建excel的node
*/
@Override
protected Node createNode(Object target) {
return new ExcelNode(target);
}
/**
* 創建sheet的內容
*/
public void createSheetContent(List<? extends Object> list)
{
this.initTreeNodes(list);
this.processTreeNodes(this.treeNodes);
}
private void processTreeNodes(List nodes)
{
for (int i = 0;nodes!=null&& i < nodes.size(); i++) {
ExcelNode node=(ExcelNode) nodes.get(i);
this.processTreeNode(node);
}
}
private void processTreeNode(ExcelNode node)
{
//设置单元格内容
this.setCellContent(workbook, sheet, this.getRow(node.getRowNumber()), this.getCell(node.getRowNumber(), node.getCellNumber()), node);
//合并单元格
this.combineByExcelNode(node);
this.processTreeNodes(node.getChilds());
}
/**
* 把要處理的數據轉化成tree狀
* @param list
*/
private void initTreeNodes(List<? extends Object> list)
{
this.treeNodes=this.process(list);
for (int i = 0;treeNodes!=null &&i < treeNodes.size(); i++) {
ExcelNode node=(ExcelNode) treeNodes.get(i);
node.init(this.treeNodes);
}
}
/**
* 得到row
* @param rowNumber
* @return
*/
protected HSSFRow getRow(int rowNumber)
{
HSSFRow row=this.rowCache.get(String.valueOf(rowNumber));
if(null==row)
{
row=this.sheet.createRow(rowNumber);
this.rowCache.put(String.valueOf(rowNumber), row);
}
return row;
}
/**
* 得到cell
* @param rowNumber
* @param cellNumber
* @return
*/
protected HSSFCell getCell(int rowNumber ,int cellNumber )
{
String key=rowNumber+"_"+cellNumber;
HSSFCell cell=this.cellCache.get(key);
if(null==cell)
{
HSSFRow row=this.getRow(rowNumber);
cell=row.createCell(cellNumber);
this.cellCache.put(key, cell);
}
return cell;
}
/**
* 根据node合并单元格
* @param node
*/
protected void combineByExcelNode(ExcelNode node)
{
this.sheet.addMergedRegion(new Region((short) node.getRowFrom(), (short) node.getCellFrom(), (short)node.getRowTo(), (short) node.getCellTo()));
}
/**
* 設置這個單元格的數據
* @param workbook
* @param sheet
* @param row
* @param cell
* @param node
*/
public abstract void setCellContent(HSSFWorkbook workbook, HSSFSheet sheet,HSSFRow row,HSSFCell cell,ExcelNode node);
}