cla*_*234 42
我知道这是一个古老的问题,但我一直在寻找解决方案,并认为我会发布它以防其他人需要它.
我不确定为什么FAQ没有提到这一点,因为它在文档中非常明显.
我的代码如下所示:
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
Run Code Online (Sandbox Code Playgroud)
c
存储创建的列数
单元格只是一个临时占位符,返回的CellView
对象
表是我的WriteableSheet
对象
Api警告说这是一个处理器密集型功能,所以它可能不适合大文件.但对于像我这样的小文件(<100行),它没有花费明显的时间.
希望这有助于某人.
neu*_*sys 14
该方法是自我解释和评论:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
Run Code Online (Sandbox Code Playgroud)
它很好,而不是扫描所有列.将列作为参数传递.
void display(column)
{
Cell = sheet.getColumnView(column);
cell.setAutosize(true);
sheet.setColumnView(column, cell);
}
Run Code Online (Sandbox Code Playgroud)
因此,当您显示文本时,您可以设置特定长度.可以为巨大的excel文件提供帮助.
来自 JExcelApi常见问题解答
如何执行与 Excel 的“格式/列/自动调整选择”等效的操作?
没有 API 函数可以为您执行此操作。您需要编写代码来扫描每列中的单元格,计算最大长度,然后相应地调用 setColumnView()。这将使您接近 Excel 的功能,但不完全一样。由于大多数字体具有可变宽度字符,为了获得完全相同的值,您需要使用 FontMetrics 来计算列中每个字符串的最大宽度。目前还没有人发布关于如何执行此操作的代码。请随时将代码发布到 Yahoo! 分组或直接发送至本页底部列出的常见问题解答作者。
FontMetrics 大概是指java.awt.FontMetrics。您应该能够使用我所拥有的 getLineMetrics(String, Graphics) 方法来解决一些问题。