码迷,mamicode.com
首页 > 编程语言 > 详细

Java使用jxl对excel文件进行简单的读写

时间:2014-12-30 20:43:02      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:java excel jxl

jxl的Jar包下载地址:百度网盘


import java.io.File;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * 
 * 2014年12月30日 下午7:16:14
 * @author sunfeilong1993
 * 简介:利用jxl实现简单的从excel文件中读取数据和那数据写入到excel文件中
 * 
 */

public class ExcelInputAndOutput {
	public static void main(String[] args) {
		writeToFile();
		readFromFile();
	}
	
	
	//readFromFile
	public static void readFromFile(){
		File file = new File("d:/test.xls");
		StringBuffer sb = new StringBuffer();
		try {
			
			Workbook book = Workbook.getWorkbook(file);
			try{
				
				Sheet sheet = book.getSheet(0);
				for(int i = 0 ; i < 10 ; i++){
					for(int j = 0 ; j < 10 ; j++){
						//第一个参数代表列,第二个参数代表行。(默认起始值都为0)
						sb.append(sheet.getCell(j, i).getContents()+"\t");
					}
					sb.append("\n");
				}
				System.out.println(sb);
			}finally{
				if(book != null){
					book.close();
				}
			}
			
		} catch (BiffException e) {
			System.err.println(e+"");
		} catch (IOException e) {
			System.err.println(e+"文件读取错误");
		}
	}//end readFromFile
	
	//witeToFile
	public static void writeToFile(){
		File file = new File("d:/test.xls");
		try {
			
			WritableWorkbook book = Workbook.createWorkbook(file);
			//创建一个工作区。(默认的excel文件有三个sheet,在excel的左下角可以看到sheet1/sheet2/sheet3)
			WritableSheet sheet = book.createSheet("第一页", 0);
			//在工作区上面添加内容
			try {
				for(int i = 0; i < 10 ; i ++ ){
					for(int j = 0 ; j < 10 ; j++){
						Label newLabel;
						if(0 == i){
							//第一个参数代表列,第二个参数代表行(默认起始值都为0),第三个参数是要在单元格里面填写的内容发
							newLabel = new Label(j,i,String.valueOf(j));
						}else if(0 == j){
							newLabel = new Label(j,i,String.valueOf(i));
						}else{
							newLabel = new Label(j,i,String.valueOf(i*j));
						}
						//在单元格上面添加注释
						WritableCellFeatures cellFeatures = new WritableCellFeatures();
						cellFeatures.setComment("这里是"+i+"*"+j+"的值");
						newLabel.setCellFeatures(cellFeatures);
						sheet.addCell(newLabel);
					}
				}
			} catch (RowsExceededException e) {
				System.err.println(e+"行或列参数错误!");
			} catch (WriteException e) {
				System.err.println(e+"写入失败");
			}finally{
				if(book != null){
					book.write();
					try {
						book.close();
					} catch (WriteException e) {
						System.err.println(e+"文件关闭失败!");
					}
				}
			}
			
		} catch (IOException e) {
			System.err.println(e+"创建文件失败!");
		}
	}
	
	
}


Java使用jxl对excel文件进行简单的读写

标签:java excel jxl

原文地址:http://blog.csdn.net/sunfeilong1993/article/details/42271153

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!