2009-11-03 249 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); 
    } 
}