package com.test.excel;
import java.io.File; import java.io.IOException;
import jxl.Workbook; import jxl.format.Border; import jxl.format.Colour; import jxl.format.UnderlineStyle; import jxl.format.BorderLineStyle; import jxl.write.Formula; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCell; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException;
public class TestExcel {
public static void writeExcel(File file) { try { //创建一个Excel文档
WritableWorkbook workbook = Workbook.createWorkbook(file); //创建一个Sheet
WritableSheet sheet = workbook.createSheet("Report-1", 0); //是否显示网格
sheet.getSettings().setShowGridLines(true); //设置列宽
sheet.getSettings().setDefaultColumnWidth(9); //设置行高
sheet.getSettings().setDefaultRowHeight(500);
Label label = new Label(1, 1, "This is a Lable"); sheet.addCell(label); //设置字体
WritableFont font = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED); WritableCellFormat cFormat = new WritableCellFormat(font); //设置背景色
cFormat.setBackground(Colour.LIGHT_BLUE); Label label2 = new Label(5, 13, "hello new Label", cFormat); sheet.addCell(label2); WritableSheet sheet2 = workbook.createSheet("report-2", 1);
WritableCellFormat newFormat = new WritableCellFormat(); newFormat.setBorder(Border.ALL, BorderLineStyle.DOUBLE); Label label3 = new Label(3, 6, "border", newFormat); sheet.addCell(label3);
Formula l3 = new Formula(10, 10, "=SUM(C4:C5)");
//公式暂未成功,本来准备计算l1与l2的和,并显示到l3,未成功
//WritableCell cell = l3.copyTo(2, 5);
Number l1 = new Number(2, 3, 3); Number l2 = new Number(2, 4, 4);
sheet.addCell(l1); sheet.addCell(l2); //sheet.addCell(cell);
workbook.write(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } }
public static void main(String args[]) { File file = new File("d:/test.xls"); writeExcel(file); } }
|