JXL单元格格式

如何使用jxl API自动调整单元格中的内容?

我知道这是一个古老的问题,但我正在寻找解决scheme,并认为我会张贴,以防其他人需要它。

CellView自动大小

我不确定为什么FAQ没有提到这个,因为它在文档中非常清楚。

我的代码如下所示:

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

c存储创build的列数
单元格只是返回的CellView对象的临时占位符
工作表是我的WriteableSheet对象

Api警告说,这是一个处理器密集型function,所以它可能不适合大文件。 但对于像我这样的小文件(<100行),没有花费很多时间。

希望这有助于某人。

该方法是自我解释和评论:

 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); } } 
 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文件。

从JExcelApi 常见问题

我如何做Excel的“格式/列/自动拟合select”equivilent?

没有API函数为你做这个。 您需要编写代码扫描每列中的单元格,计算最大长度,然后相应地调用setColumnView()。 这会让你接近Excel的function,但不完全一样。 由于大多数字体都具有可变宽度字符,要获取完全相同的值,则需要使用FontMetrics来计算列中每个string的最大宽度。 没有人发布如何做到这一点的代码呢。 随意将代码发布到Yahoo! 组或直接发送到本页底部列出的常见问题解答作者。

FontMetrics推测是指java.awt.FontMetrics 。 你应该可以用getLineMetrics(String,Graphics)方法解决问题。

CellView的autosize方法一直不适用于我。 我这样做的方式是通过编程方式设置列的大小(宽度)的基础上列的数据的最高长度。 然后执行一些math运算。

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

其中highest是保存列中数据的最长长度的整数。

如果您的单元格超过255个字符,setAutosize()方法将无法工作。 这与Excel 2003最大列宽指定相关: http : //office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP005199291.aspx

您将需要编写自己的autosize方法来处理这种情况。

试试这个例子:

  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); } }