public class ExportExcel {
public static void main(String[] args) {
try {
writeExcel("G:\\ce1.xls");
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 导出报表
* @param currentPage
* @param loan
* @param model
* @return
*/
public static void writeExcel(String fileName) throws RowsExceededException{
WritableWorkbook wwb = null;
try {
//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if(wwb!=null){
//创建一个可写入的工作表
//Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
//给sheet电子版中所有的列设置默认的列的宽度;
// ws.getSettings().setDefaultColumnWidth(30);
//设置字体;
WritableFont font1=
new WritableFont(WritableFont.TIMES,16);
//设置字体;
WritableFont font2 =
new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.RED);
WritableCellFormat format1 = new WritableCellFormat(font1);
WritableCellFormat format2 = new WritableCellFormat(font2);
try {
//设置背景颜色;
format1.setBackground(Colour.BLUE_GREY);
//设置边框;
format1.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
//把水平对齐方式指定为居中
format1.setAlignment(jxl.format.Alignment.CENTRE);
//把垂直对齐方式指定为居中
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//设置自动换行
format1.setWrap(true);
} catch (WriteException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//列设置不同的宽度;
ws.setColumnView(0, 50);
Label labelC1 = new Label(0,0,"订单号");
Label labelC2 = new Label(1,0,"客户姓名");
Label labelC3 = new Label(2,0,"备注");
try {
//添加到行中;
ws.addCell(labelC1);
ws.addCell(labelC2);
ws.addCell(labelC3);
} catch (RowsExceededException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (WriteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//下面开始添加单元格
List<Loan> loans = new ArrayList<Loan>();
Loan loan1 = new Loan();
Loan loan = new Loan();
loan1.setLoanNumber("ytqb11111111111");
loan1.setRealName("李四");
loan1.setRemark("aaaaa");
loans.add(loan1);
loan.setLoanNumber("ytqb2222222222222222");
loan.setRealName("账上");
loan.setRemark("bbbbb");
loans.add(loan);
loans.add(loan);
loans.add(loan);
for(int i = 0; i < loans.size(); i++) {
Label labelC4 = new Label(0,i+1,loans.get(i).getLoanNumber(),format1);
Label labelC5 = new Label(1,i+1,loans.get(i).getRealName(),format2);
Label labelC6 = new Label(2,i+1,loans.get(i).getRemark());
ws.setRowView(i+1, 500);
try {
//添加到行中;
ws.addCell(labelC4);
ws.addCell(labelC5);
ws.addCell(labelC6);
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//从内存中写入文件中
wwb.write();
//关闭资源,释放内存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}
Jxl操作Excel设置背景、字体颜色、对齐方式、列的宽度
最新推荐文章于 2021-01-13 11:05:05 发布