2 回答

TA貢獻1828條經驗 獲得超3個贊
不要以那種復雜的方式繪制邊框。
如果想這樣做(使用單個CellStyle
s),則需要創建 8 個單個單元格樣式。一種具有左上邊緣的邊框,一種具有上線的邊框,一種具有右上邊緣的邊框,一種具有左線的邊框,一種具有右線的邊框,一種具有左下邊緣的邊框,一種具有邊框底線和一個具有右下邊緣的邊框。然后,在創建單元格并用內容填充它們之后,必須將正確的單元格樣式(之前創建的 8 個中的一個)應用于單元格。
這是丑陋和復雜的編碼。所以人們經常做你所做的事情,只是為每個單元格創建一個新的單元格樣式。但是Excel
在獨特的單元格格式/單元格樣式的數量上是有限的。請參閱Excel 規范和限制。因此,擁有包含大量數據的大工作表,很容易超過 64,000 種獨特單元格格式/單元格樣式的限制。因此,簡單地為每個單元格創建一個新的單元格樣式是錯誤的。
Busy Developers' Guide to HSSF and XSSF Features中的繪制邊框展示了如何做得更好。
完整示例:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class ExcelDrawingBorders {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("ExcelDrawingBorders.xlsx") ) {
int startDataRow = 4;
int endDataRow = 8;
int startDataColumn = 2;
int endDataColumn = 6;
Sheet sheet = workbook.createSheet();
for (int r = startDataRow; r <= endDataRow; r++) {
Row row = sheet.createRow(r);
for (int c = startDataColumn; c <= endDataColumn; c++) {
Cell cell = row.createCell(c);
cell.setCellFormula("RANDBETWEEN(10,50)");
}
}
PropertyTemplate propertyTemplate = new PropertyTemplate();
propertyTemplate.drawBorders(new CellRangeAddress(startDataRow-1, endDataRow+1, startDataColumn-1, endDataColumn+1),
BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
propertyTemplate.applyBorders(sheet);
workbook.write(fileout);
}
}
}
結果:
在這里,PropertyTemplate和CellUtil為您完成了全部工作。PropertyTemplate
創建所需的屬性s Map
。在應用于工作表時,它使用CellUtil
它在工作簿級別創建 8 種所需的單元格樣式并將它們應用于正確的單元格。即使不存在但需要的單元格也會被創建。

TA貢獻1786條經驗 獲得超13個贊
代碼示例
PropertyTemplate ptT = new PropertyTemplate();
ptT.drawBorders(new CellRangeAddress(3, 3, 2, 6),
BorderStyle.THICK, BorderExtent.TOP);
ptT.applyBorders(sheet);
PropertyTemplate ptL = new PropertyTemplate();
ptL.drawBorders(new CellRangeAddress(3, 9, 2, 2),
BorderStyle.THICK, BorderExtent.LEFT);
ptL.applyBorders(sheet);
PropertyTemplate ptR = new PropertyTemplate();
ptR.drawBorders(new CellRangeAddress(3, 9, 6, 6),
BorderStyle.THICK, BorderExtent.RIGHT);
ptR.applyBorders(sheet);
PropertyTemplate ptB = new PropertyTemplate();
ptB.drawBorders(new CellRangeAddress(9, 9, 2, 6),
BorderStyle.THICK, BorderExtent.BOTTOM);
ptB.applyBorders(sheet);
添加回答
舉報