繁体   English   中英

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

[英]I want to arrange entire cells in specific column, instead of individual cells

我使用了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);

我的英语水平有点尴尬。 感谢您的阅读。 如果有什么奇怪的事,请告诉我。

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

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

第二: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) {
  }
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM