public class ExcelHandler {
private String filePath = null;
/**
*
* @param filePath related file path, "test_data/yxwTest.xls"
*/
public ExcelHandler(String filePath){
this.filePath = filePath;
}
/**
*
* @param tableHead - table header at first row, {"vendor_id", "barcode"}
* @param content - cell content, {{"550","yxw_1"},{"999999999","yxw_2"},{"891","yxw_3"}}
*/
public void createExcelFileWithContent(String[] tableHead, String[][] content) {
try{
File file = new File(filePath);
if ( !file.exists() ){
file.createNewFile();
}
WritableWorkbook workbook = null;
workbook = Workbook.createWorkbook(new File(filePath));
int columeCount = tableHead.length;
int rowCount = content.length;
WritableSheet sheet = workbook.createSheet("sheet name",0);
for(int col=0; col<columeCount; col++){
for (int row=0; row <rowCount+1; row++){
if(row == 0){
//Labels
sheet.addCell(new jxl.write.Label(col, 0, tableHead[col]));
} else {
//Content
sheet.addCell(new jxl.write.Label(col, row, content[row-1][col]));
}
}
}
workbook.write();
workbook.close();
}catch(Exception e){
e.printStackTrace();
};
}
/**
*
* @param columnNum
* @param rowNum
* @param content
*/
public void updateCell(int columnNum, int rowNum, String content) {
try {
WritableWorkbook book = null;
// Excel 获取文件
Workbook wb = Workbook.getWorkbook(new File(filePath));
// 打开文件副本,并指定数据写回原文件
book = Workbook.createWorkbook(new File(filePath), wb);
WritableSheet wsheet = book.getSheet(0);
wsheet.addCell(new jxl.write.Label(columnNum, rowNum, content));
book.write();
book.close();
} catch (BiffException be) {
be.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException re) {
re.printStackTrace();
} catch (WriteException we) {
we.printStackTrace();
}
}
}
java 操作excel
最新推荐文章于 2024-07-25 08:16:40 发布