我想安排整个单元格在特定的列,而不是单个单元格

我用POI并试图安排一整列。 但只有我发现的方式是安排个人单元格。 虽然我find了sheet.setDefaultColumnStyle()并试图使用这个函数,但它根本不起作用。 你可以让我知道使用setDefaultColumnStyle()或其他方式的方式。

下面的代码是我的代码来安排个人单元格。

  xlsxFile = new File("data.xlsx"); wb = new XSSFWorkbook(); cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); row = sheet1.createRow(0); cell = row.createCell(1); cell.setCellValue("name"); cell.setCellStyle(cellStyle); 

我的英语技能有点尴尬。 感谢您的阅读。 如果有什么奇怪的,请让我知道。

这似乎是Apache POI中的一个错误。 有两个问题:

首先:在使用Sheet.setDefaultColumnStyle和定义alignment的样式之后,POI没有在styles.xmlxf元素的标签中设置applyAlignment="true" 。 但它应该,因为只有这将导致Excel将该样式的alignment应用到新的单元格。

第二:POI本身不会将该样式应用于该列中的新单元格。 它应该在Sheet1.xml的相应c标签中设置s="1" ,其中1是样式编号。

所以我们必须解决:

 import org.apache.poi.xssf.usermodel.*; import org.apache.poi.ss.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; class CenteredColumn { public static void main(String[] args) { try { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Sheet1"); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); sheet.setDefaultColumnStyle(1, cellStyle); //Workaround 1: We set setApplyAlignment(true) into the `xf` element's tag in styles.xml. //This causes Excel applying alignments from this style to new cells in that column. for (int i = 0; i < ((XSSFWorkbook)wb).getStylesSource().getNumCellStyles(); i++) { if (((XSSFWorkbook)wb).getStylesSource().getStyleAt(i).equals(cellStyle)) { ((XSSFWorkbook)wb).getStylesSource().getCellXfAt(i).setApplyAlignment(true); } } Row row = sheet.getRow(0); if (row == null) row = sheet.createRow(0); Cell cell = row.getCell(1); if (cell == null) cell = row.createCell(1); cell.setCellValue("name"); //Workaround 2: We set the cellStyle to the new cell because POI will not do this itself. cell.setCellStyle(cellStyle); FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); wb.write(fileOut); } catch (IOException ioex) { } } }