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

jxl使用例子

程序员文章站 2022-05-31 21:41:59
...
package testExcel;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import jxl.Workbook;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class TestExcel {

	public static void main(String[] args) {
		new TestExcel().generateNewByModal();
	}
	
	/**
	 * 完全新建一个新的Workbook
	 */
	public void createNew() {
		// 创建存储文件
		try {
			String tempDownFullName = "d:/test.xls";
			WritableWorkbook workbook = Workbook.createWorkbook(new File(
					tempDownFullName));

			WritableSheet sheet = workbook.createSheet("sheet1", 0);

			Label label = null;

			WritableCellFormat wcf = new WritableCellFormat();
			wcf.setBackground(Colour.RED);

			label = new Label(1, 0, "biaoti", wcf);

			// sheet添加内容
			sheet.addCell(label);

			// wb保存
			workbook.write();
			workbook.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 根据模板新建一个workbook
	 */
	public void generateNewByModal() {

		try {
			WritableWorkbook writableWorkbook = null;

			String tempModalFullName = "d:/test.xls";
			String newFileFullName = "d:/testNew.xls";

			// 取得模板文件流
			InputStream input = new FileInputStream(tempModalFullName);
			Workbook modalbook = Workbook.getWorkbook(input);

			// 生成新的workbook
			writableWorkbook = Workbook.createWorkbook(
					new File(newFileFullName), modalbook);

			// 创建存储文件
			// workbook = Workbook.createWorkbook(new File(tempDownFullName));

			WritableSheet sheet = writableWorkbook.getSheet("sheet1");

			Label label = null;

			CellFormat cf = sheet.getCell(1, 0).getCellFormat();

			// sheet.getCell(1, 0).
			WritableCellFormat wcf = new WritableCellFormat(cf);

			label = new Label(1, 0, "biaoti", wcf);
			label.setCellFormat(cf);
			wcf.setBackground(Colour.BLUE);
			sheet.addCell(label);

			writableWorkbook.write();
			writableWorkbook.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
 
 
需要jxl JAR包的支持,我的是1.0版本。
 
 
 
ps:发现一个讲的比较好的jxl的例子:http://yanick.iteye.com/blog/319394
----------------------------
ps:jxl是从0开始的(记忆技巧:程序都是从0开始的),而excel是从1开始的