根据Excel文件中的内容,修改指定文件夹下的文件名称

问题:根据Excel文件中内容,把文件名称由第2列,改为第1列。比如:把文件“123.jpg”修改为“1.jpg”。

   思路1:按行读取Excel文件,同时遍历文件;修改文件名称。(双层for循环,效率:n*n)

* 思路2:把文件以Map的形式进行一一存储;读取Excel文件,从Map中取得文件;修改文件名称。(效率:n+n)


 

/**
* 描述:根据Excel中的内容,修改目标路径下的文件名称
* @param excelFile 源Excel文件(最原始文件,3列的)
* @param path 文件夹的路径
* @param column 表格中的第几列。0序号;2姓名
* @throws CheckException
*/
public static void updateFileName(File excelFile,File path,Integer column) throws CheckException{
checkExcelFile(excelFile);
if(path.listFiles()==null){
throw new CheckException("照片文件不存在!");
}
//1.遍历文件,把文件存储至 Map中。键:文件名称(无后缀),值:文件
File[] files=path.listFiles();
Map<String,File> fileMap=new HashMap<String,File>();
for(File file:files ){
String name=file.getName();
String prefixPhoto=name.substring(0,name.lastIndexOf('.'));
fileMap.put(prefixPhoto,file);
}

try{
    //2.遍历Excel文件
Workbook workbook=new HSSFWorkbook(new FileInputStream(excelFile));
Sheet sheet = workbook.getSheetAt(0); // 从工作区中取得页(Sheet)
int rowEnd = sheet.getLastRowNum();
for (int i = 0; i < rowEnd; i++) {//行 循环打印Excel表中的内容
Row row = sheet.getRow(i);
String idcard = row.getCell(1).getStringCellValue();//(列,行)
File photoFile=fileMap.get(idcard);
       //3.修改文件名称
if(photoFile!=null){
String fileName=photoFile.getName();
String subfixPhoto=fileName.substring(fileName.lastIndexOf('.'));
row.getCell(column).setCellType(Cell.CELL_TYPE_STRING);//设置Excel文件中单元格内容的类型为String类型
String text = row.getCell(column).getStringCellValue();
photoFile.renameTo(new File(photoFile.getParent()+"\\"+text+subfixPhoto));//修改文件名称
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
posted @ 2016-11-08 11:07  小妮儿玩博客  阅读(2506)  评论(0编辑  收藏  举报