欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java使用jxl导出Excel

程序员文章站 2022-04-09 10:48:11
...

jxl.jar是通过java操作excel表格的工具类库,是由java语言开发而成的,只能生成.xls格式

Maven依赖:

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

案例1:

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;


//创建列名
String[] title={"id","num1","num2","string1"};
//创建文件
File file=new File("d:/"+System.currentTimeMillis()+".xls");
try {
    file.createNewFile();
    //创建工作簿
    WritableWorkbook workbook= Workbook.createWorkbook(file);
    //创建sheet
    WritableSheet sheet=workbook.createSheet("这里是sheet1", 0);
    //设置列宽
    List<Integer> columnView = Arrays.asList(22,19,19,19);
    //第一行设置列名
    for(int i=0;i<title.length;i++){
        Label label=new Label(i,0,title[i]);
        WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 11 , WritableFont.BOLD);
        WritableCellFormat wcf=new WritableCellFormat(font);
        wcf.setBackground(Colour.SKY_BLUE);// 设置单元格的背景颜色
	    wcf.setAlignment(Alignment.CENTRE); // 设置对齐方式
	    label.setCellFormat(wcf);
	    sheet.setColumnView(i, columnView.get(i)); // 设置列的宽度
	    sheet.addCell(label);
    }
    //追加数据
    List<String> a = Arrays.asList("1","2","3");
    List<String> b = Arrays.asList("1","2","3","4","5","6","7","8","9","10","11","12");
    List<String> s = Arrays.asList("1","2","3","4");
    //以id为一条数据,c是获取id的下标
    int c=0;
    WritableCellFormat wcf=new WritableCellFormat();
    // 设置对齐方式
    wcf.setAlignment(Alignment.CENTRE);
    wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
    //i是下一个id数据开始的行数
    for (int i=0;i<b.size();){
	    //A列
	    Label label=null;
	    label=new Label(0,i+1,a.get(c));
	    label.setCellFormat(wcf);
	    sheet.mergeCells(0,i+1,0,i+s.size());
	    sheet.addCell(label);
	    //C列
	    label=new Label(2,i+1,(i+1)+",3");
	    label.setCellFormat(wcf);
	    sheet.mergeCells(2,i+1,2,i+s.size());
	    sheet.addCell(label);
	    //D列
	    label=new Label(3,i+1,(i+1)+",432edsasasd,ferf8y93892398dne,dewewijdewihd8923982,e32u89duew9dewiodewiodnewiomdwdmewoidjwe89u8923enjnfijrefnurefher78yf78f38r3findifwncuiewhfeu8fhe8");
	    label.setCellFormat(wcf);
	    sheet.mergeCells(3,i+1,3,i+s.size());
	    sheet.addCell(label);
	    //B列
	    for (int j = 0; j < s.size(); j++) {
		    label=new Label(1,i+1+j,s.get(j));
		    label.setCellFormat(wcf);
		    sheet.addCell(label);
	    }
	    c++;
	    i=i+s.size();
    }
    //写入数据
    workbook.write();
    workbook.close();
} catch (Exception e) {
    e.printStackTrace();
}

输出结果:

id num1 起始位置 string1
1 1 (1,3) 1-哈哈
2
3
4
2 1 (5,3) 5-哈哈
2
3
4
3 1 (9,3) 9-哈哈
2
3
4

备注:

      真实输出的表格没有一行一个颜色的效果,这是CSDN编辑器自带的。