我想要在特定的列中整齐排列所有单元格,而不是单独排列每个单元格。

3
我使用了POI并尝试整列排列。但是我找到的方式只能安排单个单元格。虽然我找到了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);

我的英语能力有些生疏。感谢您的阅读。如果有任何奇怪的地方,请告诉我。


1
我不知道你所说的“整理一整列”是什么意思。 - arcy
这意味着将文本对齐到单元格中间。另一种表达方式是将水平居中对齐到一个列上。 - Mr.choi
1个回答

4

这似乎是Apache POI中的一个bug。存在两个问题:

第一:在使用Sheet.setDefaultColumnStyle并定义了对齐方式的样式后,POI没有在styles.xmlxf元素的标签中设置applyAlignment="true"。但它应该这样做,因为只有这样Excel才会将该样式的对齐方式应用于新单元格。

第二:POI本身不会将此样式应用于该列的新单元格。它应该在Sheet1.xml的相应标签中设置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) {
  }
 }
}

1
你能否在Apache POI bugzilla中报告这个问题,并附上/列出你的调查和建议的修复措施? - Gagravarr
已经存在类似的错误:https://bz.apache.org/bugzilla/show_bug.cgi?id=51037。我发现至少 Excel 2007 本身足够宽容,即使在 styles.xml 中没有 applyAlignment="true",也可以应用对齐方式。只有 Libreoffice Calc 不行。但是 Libreoffice 不是 POI 的目标。因此,我们必须使用所示的解决方法。至于在 POI 中将 DefaultColumnStyle 应用于该列中的新单元格的缺失应用,在链接的错误的评论 9 中清楚地表明这将不会被修复。 - Axel Richter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接