解析Excel文件
创建Excel
package hcz.resolve.excel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ResolveExcel {
/**
* hcz 2012-08-15 解析Excel文件
* 引用jxl.jar
*/
public static void main(String[] args) {
File file =new File("E:\\temp\\my.xls");
resolveExcel(file);
}
private static void resolveExcel(File file) {
Workbook book = null;
try {
//创建一个Workbook对象
book = Workbook.getWorkbook(file);
//得到第一个sheet工作表
Sheet sheet = book.getSheet(0);
//一共多少行
int rows = sheet.getRows();
//一共多少列
int columns = sheet.getColumns();
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
// System.out.println(j+" "+i); //解析构造
System.out.print(sheet.getCell(j, i).getContents()+" ");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭文件
book.close();
}
}
}
创建Excel
package hcz.resolve.excel;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class WriteExcel {
/**
* hcz 2012-08-15 写入文字到Excel文件
* 引用jxl.jar
*/
public static void main(String[] args) {
//创建存放文件的路径,如果不存在则自己创建
File path = new File("E:\\temp\\");
if(!path.exists()){
path.mkdirs();
}
//在制定路径下创建Excel文件
File file = new File("E:\\temp\\my.xls");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
createExcel(file);
}
public static void createExcel(File file){
WritableWorkbook book = null;
try {
book = Workbook.createWorkbook(file);
//创建一页sheet工作表
WritableSheet sheet =book.createSheet("第1页", 0);
//第一行,第一列,写入字符串test
Label lable = new Label(0,0,"test");
sheet.addCell(lable);
//第一行,第二列,写入数字型123
jxl.write.Number num = new jxl.write.Number(1,0,123);
sheet.addCell(num);
jxl.write.DateTime date = new jxl.write.DateTime(2,0,new Date());
sheet.addCell(date);
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}finally{
try {
book.write();
book.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}