try{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("c:/a.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
// 这个判断很必要 确保下面cell操作顺利执行
if(row == null){
row = sheet.createRow(0);
}
HSSFCell cell = row.getCell(1, Row.RETURN_NULL_AND_BLANK);
if(cell == null){
cell = row.createCell(1,HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("hahaha");
// 保存修改
FileOutputStream fileOut = new FileOutputStream("c:/a.xls");
wb.write(fileOut);
fileOut.close();
}else{
System.out.println(cell.getStringCellValue());
}
}catch(Exception e){
e.printStackTrace();
}
// 获取指定cell的值 如:G5
CellReference ref = new CellReference("G5");
HSSFCell cell = sheet.getRow(ref.getRow()).getCell(ref.getCol());
System.out.println(cell.getStringCellValue());
// 设置指定cell的值 如:G5
CellReference ref = new CellReference(“G5”);
sheet.getRow(ref.getRow()).getCell(ref.getCol()).setCellValue("haha");
// 单元格合并 from:A1 to:F10
CellReference rFrom = new CellReference(from);
CellReference rTo = new CellReference(to);
sheet.addMergedRegion(new CellRangeAddress(rFrom.getRow(),rTo.getRow(),rFrom.getCol(),rTo.getCol()));
// 设置cell为日期格式
HSSFDataFormat format = this.wb.createDataFormat();
style.setDataFormat(format.getFormat(“m月d日”));
row.createCell(i).setCellStyle(style);
// 单元格是否加锁
HSSFCellStyle style = wb.createCellStyle();
style.setLocked(false); // true加 false不加
// 设置货币型(3位一逗号)
HSSFDataFormat format = wb.createDataFormat();
HSSFCellStyle style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0"));
cell.setCellStyle(style);
cell.setCellValue(888888988);
// 出力excel时,模板里有现成的sum公式,但出力后不自动计算的解决办法
getWorkBook().getSheetAt(OUTPUT_SHEET_INDEX).setForceFormulaRecalculation(true);