package excelUtil;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class SingleExcel {
/**
* @author
* @date 2017 06 13
* @descripte 用于对Excel 的操作的工具 此处用的工具是jxl
*
* 1.针对一个excel一个sheet生成一个线程
*/
public static void main(String[] args) {
//用于测试
}
private static WritableWorkbook book=null;
private static WritableSheet sheet=null;
//通过地址获得Excel 如果该地址没有找到excel
//@ excPath Excel的路径
//creratExcel 如果不存在 是否新建excel
public void getBook(String excPath,boolean creratExcel){
File file=new File(excPath);
if(!file.exists()&&creratExcel)
try {
file.createNewFile();
book=Workbook.createWorkbook(file);
} catch (IOException e) {
e.printStackTrace();
}
}
//sheetName sheet的名称
//createExcel 如果存在是删除后新建还是返回存在的
public void getNewSheet(String sheetName,boolean createExcle){
WritableSheet[] sheets=book.getSheets();
for(int i=0;i
WritableSheet sheet=sheets[i];
if(sheet.getName().equals(sheetName)){
if(createExcle){
book.removeSheet(i);
sheet=book.createSheet(sheetName,book.getSheets().length);
}else{
sheet=sheets[i];
}
break;
}
}
}
//写入数据 并关闭book sheet
public void close(){
try {
book.write();
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//写入单元格内容
public void wirte2Cell(String contain,int row ,int cow){
Label label=new Label(cow, row, contain);
try {
sheet.setColumnView(cow, setView());
sheet.addCell(label);
} catch (Exception e) {
e.printStackTrace();
}
}
//设置sheet 样式 自动调整单元格
private static CellView setView(){
CellView view=new CellView();
view.setAutosize(true);
return view;
}
//读取excel中的信息(已经得到sheet) 获取指定行 指定列
public Object getCell(int row,int cow){
Cell cell=sheet.getCell(cow, row);//getCell(列, 行)
return cell.getContents();
}
//读取excel中的信息 并到一个二维数组里面
public Object[][] getcells(){
Object[][] obj=new Object[sheet.getRows()][sheet.getColumns()];
for(int i=0;i
for(int j=0;j
obj[i][j]=sheet.getCell(j, i).getContents();
}
}
return obj;
}
}