2009-11-03 97 views

回答

2

從JExcelApi的FAQ

我該怎麼做Excel的 「格式/列/自動調整選擇」 的equivilent?

沒有API函數可以爲您做到這一點。您需要編寫代碼掃描每列中的單元格,計算最大長度,然後相應地調用setColumnView()。這會讓你接近Excel的功能,但不完全一樣。由於大多數字體具有可變寬度字符,要獲得完全相同的值,您需要使用FontMetrics來計算列中每個字符串的最大寬度。沒有人發佈過關於如何執行此操作的代碼。隨意將代碼發佈到Yahoo!組或直接發送到本頁底部列出的常見問題解答作者。

FontMetrics推測是指java.awt.FontMetrics。你應該可以用getLineMetrics(String,Graphics)方法解決問題。

37

我知道這是一個古老的問題在這一點上,但我一直在尋找解決方案,並認爲我會張貼它,以防其他人需要它。

CellView Auto-Size

我不知道爲什麼FAQ沒有提到這一點,因爲它很清楚的文檔存在。

我的代碼看起來像下面這樣:

for(int x=0;x<c;x++) 
{ 
    cell=sheet.getColumnView(x); 
    cell.setAutosize(true); 
    sheet.setColumnView(x, cell); 
} 

c商店列數創建
細胞僅僅是返回CellView對象
片臨時佔位符是我WriteableSheet對象

Api警告說這是一個處理器密集型功能,所以它可能不適合大文件。但對於像我這樣的小文件(< 100行),它沒有花費很多時間。

希望這可以幫助別人。

+0

大......這是工作... –

+0

非常感謝你!你可以添加單元格的類型嗎?那是CellView? – sboda

2

CellView的自動調整方法不爲我工作的所有時間。我這樣做的方式是通過編程設置的列的大小(寬度)的基礎上的數據列中的最高長度。然後執行一些數學運算。

CellView cv = excelSheet.getColumnView(0); 
cv.setSize((highest + ((highest/2) + (highest/4))) * 256); 

其中highest是一個int,它保存列中數據的最長長度。

6
for(int x=0;x<c;x++) 
{ 
    cell=sheet.getColumnView(x); 
    cell.setAutosize(true); 
    sheet.setColumnView(x, cell); 
} 

這很好,而不是掃描所有的列。將列作爲參數傳遞。

void display(column) 
{ 
    Cell = sheet.getColumnView(column); 
    cell.setAutosize(true); 
    sheet.setColumnView(column, cell); 
} 

所以,當你將顯示你的文字,你可以設置特定的長度。可以是有益的巨大的Excel文件。如果您的電池有超過255個字符

11

的方法是自我解釋和評論:

private void sheetAutoFitColumns(WritableSheet sheet) { 
    for (int i = 0; i < sheet.getColumns(); i++) { 
     Cell[] cells = sheet.getColumn(i); 
     int longestStrLen = -1; 

     if (cells.length == 0) 
      continue; 

     /* Find the widest cell in the column. */ 
     for (int j = 0; j < cells.length; j++) { 
      if (cells[j].getContents().length() > longestStrLen) { 
       String str = cells[j].getContents(); 
       if (str == null || str.isEmpty()) 
        continue; 
       longestStrLen = str.trim().length(); 
      } 
     } 

     /* If not found, skip the column. */ 
     if (longestStrLen == -1) 
      continue; 

     /* If wider than the max width, crop width */ 
     if (longestStrLen > 255) 
      longestStrLen = 255; 

     CellView cv = sheet.getColumnView(i); 
     cv.setSize(longestStrLen * 256 + 100); /* Every character is 256 units wide, so scale it. */ 
     sheet.setColumnView(i, cv); 
    } 
} 
0

試試這個爲例:

expandColumns(sheet, 3); 

    workbook.write(); 
    workbook.close(); 

private void expandColumn(WritableSheet sheet, int amountOfColumns){ 
    int c = amountOfColumns; 
    for(int x=0;x<c;x++) 
    { 
     CellView cell = sheet.getColumnView(x); 
     cell.setAutosize(true); 
     sheet.setColumnView(x, cell); 
    } 
}