jxl自动设置列宽

本文介绍了使用jxl库在Java中设置Excel文件列宽的两种方法。方法一通过设置CellView的自动调整属性实现;方法二是直接设置指定宽度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


jxl中并没有提供类似setRowView(int row, boolean collapsed)的自动设置列宽的方法

但是,我们可以通过它的其他API来实现这样的效果:
方法一:
jxl的API中有这样的方法:
引用
setColumnView
void setColumnView(int col,
CellView view)Sets the view for this column

Parameters:
col - the column on which to set the view
view - the view to set


而在API中查找到CellView 有这个方法:

引用
setAutosize
public void setAutosize(boolean a)Sets the autosize flag. Currently, this only works for column views

Parameters:
a - autosize


于是,我试着这样用:
Java代码 复制代码 收藏代码spinner.gif
  1. ... ...
  2. //设置字体为Arial,30号,加粗
  3. CellView cellView = new CellView();
  4. cellView.setAutosize(true); //设置自动大小
  5. sheet.setColumnView(1, cellView);//根据内容自动设置列宽
  6. label = new Label(1, 0, "zzzzzzzzzzzzzzzzzzzzzz");
  7. sheet.addCell(label);
  8. ... ...
... ...
//设置字体为Arial,30号,加粗
CellView cellView = new CellView();
cellView.setAutosize(true); //设置自动大小
sheet.setColumnView(1, cellView);//根据内容自动设置列宽
label = new Label(1, 0, "zzzzzzzzzzzzzzzzzzzzzz");
sheet.addCell(label);
... ...

发现效果确实是实现了自动调整列宽。

方法二:
jxl的API中有与上面同名的方法:
引用
setColumnView
void setColumnView(int col,
int width)Sets the width of the column on this sheet, in characters. This causes Excel to resize

the entire column. If the columns specified already has view information associated with it, then it is replaced by

the new data

Parameters:
col - the column to be formatted
width - the width of the column

方法的第二个参数就是自己设置列宽
因此,我们可以先计算我们写入的字符串的长度,然后以这个长度作为列宽来设置,同样达到自动调整列宽的效果!
jxl中列宽值是以字符来算的,也就是列宽为1,则是一个字符的长度

于是,我试着这样用:
Java代码 复制代码 收藏代码spinner.gif
  1. ... ...
  2. //设置字体为Arial,30号,加粗
  3. label = new Label(1, 0, "zzzzzzzzzzzzzzzzzzzzzz");
  4. sheet.addCell(label);
  5. sheet.setColumnView(1, new String("zzzzzzzzzzzzzzzzzzzzzz").length());
  6. ... ...
... ...
//设置字体为Arial,30号,加粗
label = new Label(1, 0, "zzzzzzzzzzzzzzzzzzzzzz");
sheet.addCell(label);
sheet.setColumnView(1, new String("zzzzzzzzzzzzzzzzzzzzzz").length());
... ...

发现效果同样实现了自动调整列宽。

转载于:https://my.oschina.net/u/267384/blog/170478

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值