Java 如何在ApachePOI中按名称获取单元格样式

Java 如何在ApachePOI中按名称获取单元格样式,java,apache-poi,cell,Java,Apache Poi,Cell,我使用3.16 我在一个方法中创建了一些单元格样式。我将工作簿传递给另一个设置单元格值的方法 在这种情况下,我必须将所有单元格样式作为参数传递给其他方法。有没有办法只传递工作簿,并从工作簿本身获取样式 我发现 workbook.getCellStyleAt(idx). 但为此,我必须对我创建的所有样式进行索引跟踪。并硬编码它的值。如果我在两者之间为一种新样式编码,那么我可能会因为索引号的改变而弄乱图纸格式 示例代码 SXSSFWorkbook workbook = new SXSSFWorkb

我使用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;
styleBOM = CellStyleMap.getStyle("BOM");
CellStyle styleBOM;
styleBOM = CellStyleMap.getStyle("BOM");