JExcel API使用笔记
JExcel是一个开源的支持excel的java类库,广泛利用其api来生成excel报表
API基本使用
1.创建excel文件
workbook = Workbook.createWorkbook(file);//传入file文件
2.创建sheet页
WritableSheet sheet = workbook.createSheet("记录表", 0);//可以调整sheet页的名称与索引
3.创建标题栏
创建完sheet页后,我们先创建一行标题栏
sheet.addCell(new Label(c, r, fileName, arial14format));//r是行,c是列,标签内容,单元格格式
4.设置单元格行高、列宽
sheet.setRowView(0, 340); //设置行高
sheet.setColumnView(0, 45); //设置列宽
5.单元格格式设置
//字体设置
arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);//字体、大小、样式
arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);//字体颜色
arial14format = new WritableCellFormat(arial14font);
arial14format.setAlignment(jxl.format.Alignment.CENTRE);//居中
arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);//边界样式
arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);//背景颜色
6.添加普通标签
获取到WritableSheet的变量后,就能添加单元格了
sheet.addCell(new Label(5, 6, “hello”, arial14format));//在第5+1列第6+1行添加一个hello
行、列都是从0开始算的!
7.添加数字
sheet.addCell(new Number(i, j + 1, Integer.parseInt(list.get(i)), arial12format));
添加格式化后的数字
NumberFormat nf = new NumberFormat("#.##");
WritableCellFormat wcfN = new WritableCellFormat(nf);
Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
ws.addCell(labelNF);
8.添加日期
WritableCellFormat dateCellFormat = new WritableCellFormat(new DateFormat("yyyy/MM/dd HH:mm:ss"));
dateCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
dateCellFormat.setBackground(Colour.AQUA);
sheet.addCell(new DateTime(c, r, (Date) list.get(i), dateCellFormat));
9.添加链接
WritableHyperlink hyperlink = new WritableHyperlink(i, j, new URL("http://baidu.com"));
Label issueLink = new Label(i, j, "http://baidu.com", arial12format);
hyperlink.setDescription(issueLink.getContents());
sheet.addCell(issueLink);
sheet.addHyperlink(hyperlink);
10.添加Boolean对象
Boolean labelB = new jxl.write.Boolean(0, 2, false);
sheet.addCell(labelB);
11.添加图片
WritableImage wimage = new WritableImage(0, 1, 2, 2, image);//0,1分别代表x,y.2,2代表宽和高占的单元格数
//image文件或byte[]
sheet.addImage(wimage);
12.将列设置为自适应
CellView cellView = sheet.getColumnView(i);
cellView.setAutosize(true);
sheet.setColumnView(i, cellView);