2015-12-25 26 views
2

我使用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

+0

這意味着對齊文本在單元格中間。另一個表達式是在一列上對齊水平中心。 –

回答

3

這似乎是Apache POI中的一個錯誤。這裏有兩個問題:

第一:使用Sheet.setDefaultColumnStyle與定義路線樣式之後,POI不設置applyAlignment="true"styles.xmlxf元素的標記。但它應該,因爲只有這樣會導致Excel將該樣式的對齊應用到新單元格。

第二:POI本身不會將此樣式應用於該列中的新單元格。它應該設置s="1",其中1是樣式編號,在Sheet1.xml的相應c標記中。

因此,我們必須要解決:

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](http://issues.apache.org/bugzilla/buglist.cgi?product=POI)中發現一個bug,並附上/列出你的調查和建議的修復? – Gagravarr

+0

已經有類似的bug:https://bz.apache.org/bugzilla/show_bug.cgi?id = 51037。我發現至少Excel 2007本身足夠寬容,並且在styles.xml中也沒有'applyAlignment =「true」'應用對齊。只有Libreoffice Calc不是。但Libreoffice不是POI的目標。所以我們必須使用顯示的解決方法。而對於缺少應用'DefaultColumnStyle'的POI中該列中的新單元格,鏈接bug中的註釋9清楚地表明這不會被修復。 –

相關問題