您的位置:首页 > 运维架构 > Apache

Apache-POI操作Excel的一些小技巧

2013-08-20 15:19 393 查看
Apache-POI操作Excel将合并后的单元格全部填充为相同数据的一个实例。

private static void fillMergedRegion(final Sheet sheet) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
int startRow = sheet.getMergedRegion(i).getFirstRow();
int endRow = sheet.getMergedRegion(i).getLastRow();
int startColumn = sheet.getMergedRegion(i).getFirstColumn();
int endColumn = sheet.getMergedRegion(i).getLastColumn();
String value = getStringValue(sheet.getRow(startRow).getCell(startColumn));

for (int row = startRow; row <= endRow; row++) {
for (int column = startColumn; column <= endColumn; column++) {
sheet.getRow(row).getCell(column).setCellValue(value);
}
}
}
}


Apache-POI操作Excel获得单元格内容

public static String getStringValue(Cell cell) {
if (cell == null) {
return StringConst.EMPTY_STRING;
}

// get the type of cell, and transform it
if (Cell.CELL_TYPE_FORMULA == cell.getCellType()) {
switch (cell.getCachedFormulaResultType()) {
// if it is mumeric type
case Cell.CELL_TYPE_NUMERIC:

return new DataFormatter().createFormat(cell).format(cell.getNumericCellValue());
// if it is string type
case Cell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().toString();

}
}
return new DataFormatter().formatCellValue(cell);
}


Apache-POI读取Excel2003和2007/**

/**
* Read the Excel File
*
* @param file
*            Excel File
* @throws IOException
*             Error handling
*/
public DVSExcelReader(File file) throws IOException {
InputStream inputStream = null;
try {

inputStream = new FileInputStream(file);

if (file.getName().endsWith(".xls")) {
// Excel 2003
this.workbook = new HSSFWorkbook(inputStream);
} else if (file.getName().endsWith(".xlsx")) {
// Excel 2007
this.workbook = new XSSFWorkbook(inputStream);
} else {
throw new RuntimeException("Wrong file name defined!");
}

} finally {
if (inputStream != null)
inputStream.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Apache POI Excel