Chinaunix首页 | 论坛 | 博客
  • 博客访问: 898149
  • 博文数量: 282
  • 博客积分: 10843
  • 博客等级: 上将
  • 技术积分: 2435
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-01 15:23
文章分类

全部博文(282)

文章存档

2013年(1)

2012年(18)

2011年(14)

2010年(30)

2009年(48)

2008年(55)

2007年(55)

2006年(61)

分类: Java

2009-12-07 16:16:41

    jxl挺好用,代码学习留用!

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);
    }
}


阅读(2671) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-12-09 16:32:30

呵呵,最近我在做的一个小项目中正好用到了老师提到的这个方法,先前也试过了,切实挺好用.