我使用的是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");
关于java - 如何在 Apache poi 中按名称获取单元格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47692753/