[英]Copying Styles from one Excel Workbook to another
我想將一張工作簿(包括樣式)復制到新工作簿。
我嘗試迭代所有單元格和
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
newCell.setCellStyle(newCellStyle);
拋出 java.lang.IllegalStateException:超出單元格樣式的最大數量。 您最多可以在 .xls 工作簿中定義 4000 種樣式
CellStyle newCellStyle = oldCell.getCellStyle();
newCell.setCellStyle(newCellStyle);
拋出 java.lang.IllegalArgumentException:此樣式不屬於提供的工作簿。 您是否嘗試將一個工作簿中的樣式分配給不同工作簿的單元格?
復制樣式的正確方法是什么?
用包含樣式的哈希圖解決了它
HashMap<Integer, CellStyle> styleMap = new HashMap<Integer, CellStyle>();
public void copyCell(Cell oldCell, Cell newCell){
int styleHashCode = oldCell.getCellStyle().hashCode();
CellStyle newCellStyle = styleMap.get(styleHashCode);
if(newCellStyle == null){
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(styleHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
Excel 中的樣式一團糟。 如果要在工作簿之間復制工作表及其所有樣式,使用 Excel 桌面,通常只需在工作簿之間復制工作表就足夠了。 樣式將自動作為行李出現。
但是以這種方式復制的樣式也很容易被破壞並導致很多問題。 您超出限制的消息指向樣式損壞,因為沒有健康的工作簿會具有超過 4000 種樣式。
在迭代中使用以下代碼:
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
這在您用來創建新單元格的迭代中:
newCell.setCellStyle(newCellStyle);
將解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.