簡體   English   中英

如何在Apache poi中按名稱獲取單元格樣式

[英]How to get cell style by name in Apache poi

我正在使用3.16

我用一種方法創建一些單元格樣式。 然后,我將工作簿傳遞給另一種用於設置單元格值的方法。

在這種情況下,我必須將所有單元格樣式作為參數傳遞給其他方法。 有沒有一種方法,我僅傳遞工作簿並從該工作簿本身獲取樣式。

我發現

workbook.getCellStyleAt(idx).

但是為此,我必須索引我創建的所有樣式的索引。 並對其進行硬編碼。 如果我在兩者之間編寫新樣式的代碼,則由於索引號會發生變化,我可能會弄亂工作表格式。

樣例代碼

SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
SXSSFSheet sheet = workbook.createSheet("SheetName");

CellStyle styleBOM = workbook.createCellStyle();
Font fontBOM = workbook.createFont();
fontBOM.setFontHeightInPoints((short) 16);
fontBOM.setFontName("Arial");
fontBOM.setBold(false);
styleBOM.setFont(fontBOM);

CellStyle headKey = workbook.createCellStyle();
Font fontKey = workbook.createFont();
fontKey.setFontHeightInPoints((short) 11);
fontKey.setFontName("Arial");
fontKey.setBold(true);
headKey.setFont(fontKey);

CellStyle headValue = workbook.createCellStyle();
Font fontValue = workbook.createFont();
fontValue.setFontHeightInPoints((short) 11);
fontValue.setFontName("Arial");
fontValue.setBold(false);
headValue.setFont(fontValue);

valueList=someLogicToFetchValues(someInput);

downloadExcel(valueList, workbook,styleBOM, headKey,headValue)

您可以創建具有所有已創建樣式的靜態表,每種樣式均由其名稱(或您選擇的任何樣式)標識。
每次創建樣式時,都將其添加到該表中,並在需要時從同一表中讀取它。
像這樣:

class CellStyleMap
{
  public static synchronized void addStyle(String    identifier,
                                           CellStyle style)
  {
    styles.put(identifier, style);
  }

  public static synchronized CellStyle getStyle(String identifier)
  {
    return (styles.get(identifier));
  }

  private static Hashtable<String, CellStyle> styles = new Hashtable<String, CellStyle>();

} // class CellStyleMap

在您的代碼中:

CellStyle styleBOM = workbook.createCellStyle();
...
CellStyleMap.addStyle("BOM", styleBOM);

當您需要時:

CellStyle styleBOM;
styleBOM = CellStyleMap.getStyle("BOM");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM