完整代碼:
/**
* 替換Excel模板中的數據
* @param sheetName Sheet名字
* @param modelPath 模板路徑
* @param param 需要替換的數據
* @return
* @author 劉澤中
* @Date: 2015年12月11日
*/
public HSSFWorkbook replaceExcel(String sheetName,String modelPath,Map<String, Object> param){
//獲取所讀取excel模板的對象
try {
File file = new File(modelPath);
if(!file.exists()){
System.out.println("模板文件:"+modelPath+"不存在!");
}
fs = new POIFSFileSystem(new FileInputStream(file));
wb = new HSSFWorkbook(fs);
sheet = wb.getSheet(sheetName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
replaceExcelDate(param);
return wb;
}
/**
* 根據 Map中的數據替換Excel模板中指定數據
* @param param
* @author 劉澤中
* @Date: 2015年12月11日
*/
public void replaceExcelDate(Map<String, Object> param){
// 獲取行數
int rowNum = sheet.getLastRowNum();
for (int i = 0; i < rowNum; i++) {
row = sheet.getRow(i);
// 獲取行里面的總列數
int columnNum = 0;
if(row!=null){
columnNum = row.getPhysicalNumberOfCells();
}
for (int j = 0; j < columnNum; j++) {
HSSFCell cell = sheet.getRow(i).getCell(j);
String cellValue = cell.getStringCellValue();
for (Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
if(key.equals(cellValue)){
String value = entry.getValue().toString();
setCellStrValue(i, j, value);
}
}
}
}
}
/**
* 設置字符串類型的數據
* @param rowIndex--行值 從0開始
* @param cellnum--列值 從0開始
* @param value--字符串類型的數據
*
* @author 劉澤中
* @Date: 2015年12月11日
*/
public void setCellStrValue(int rowIndex, int cellnum, String value) {
HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);
cell.setCellValue(value);
}