Apache POI单元格字体异常:设置样式时意外影响其他单元格
Let me break down what's going on here and how to fix that frustrating issue where changing one cell's font messes up other unrelated cells.
Why This Happens
Excel uses shared style objects under the hood, and Apache POI mirrors this behavior. When you call cell.getCellStyle(), you're getting a reference to that shared style instance—not a copy. So if you modify that style (like setting a new font), every cell that's using that same shared style will update too. That's why your "2400 Hr Clock" cell and other pre-filled cells are changing even though you didn't touch them.
The Solution: Clone the Style First
To avoid affecting other cells while keeping the original cell's formatting (borders, alignment, etc.), you need to create a new cell style that's a copy of the original, then modify that copy. Here's how:
Instead of this (which modifies the shared style and causes unintended changes):
HSSFCellStyle dataStyle = cell.getCellStyle(); dataStyle.setFont(font);
Do this:
// Create a new, empty cell style instance HSSFCellStyle dataStyle = currentWorkbook.createCellStyle(); // Copy all existing formatting (borders, alignment, fill, etc.) from the original cell's style dataStyle.cloneStyleFrom(cell.getCellStyle()); // Set your custom font on the cloned style dataStyle.setFont(font); // Apply the modified, cloned style back to the target cell cell.setCellStyle(dataStyle);
What This Does
cloneStyleFrom()duplicates every property of the original style into your new style object—so you don't lose any pre-existing formatting like borders or cell alignment.- By modifying the cloned style instead of the original shared one, you're only changing the style for the specific cell you care about. All other cells that were using the original shared style stay untouched.
Your font creation code is already correct:
HSSFFont font = currentWorkbook.createFont(); font.setFontName("Times"); font.setFontHeightInPoints(fontSize);
You're creating a new font instance tied to your workbook, which is exactly what you need to avoid cross-cell conflicts.
内容的提问来源于stack exchange,提问作者Randi

