随手写的记录一下
package com.example.java_word;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
public class ExcelData {
private XSSFSheet sheet;
/**
* 构造函数,初始化excel数据
*
* @param filePath excel路径
* @param sheetName sheet表名
*/
ExcelData(String filePath, String sheetName) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
//获取sheet
sheet = sheets.getSheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据行和列的索引获取单元格的数据
*
* @param row
* @param column
* @return
*/
public String getExcelDateByIndex(int row, int column) {
XSSFRow row1 = sheet.getRow(row);
String cell = row1.getCell(column).toString();
return cell;
}
/**
* 根据某一列值为“******”的这一行,来获取该行第x列的值
*
* @param caseName
* @param currentColumn 当前单元格列的索引
* @param targetColumn 目标单元格列的索引
* @return
*/
public String getCellByCaseName(String caseName, int currentColumn, int targetColumn) {
String operateSteps = "";
//获取行数
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
XSSFRow row = sheet.getRow(i);
String cell = row.getCell(currentColumn).toString();
if (cell.equals(caseName)) {
operateSteps = row.getCell(targetColumn).toString();
break;
}
}
return operateSteps;
}
//打印excel数据
public void readExcelData() {
//获取行数
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//获取列数
XSSFRow row = sheet.getRow(i);
int columns = row.getPhysicalNumberOfCells();
for (int j = 0; j < columns; j++) {
String cell = row.getCell(j).toString();
System.out.println(cell);
}
}
}
//
//测试方法
public static void main(String[] args) {
//存放照片的路径
String image="D:\\迅雷下载\\image";
//存放EXcel文件的地址
String ExcelPAth="C:\\Users\\zhou\\Desktop\\学校\\studen.xlsx";
//excel文件的表名字
String name="Sheet1";
//学号在第几列,从0开始算起
int studenId=0;
//姓名在第几列,从0开始算起
int St_name=1;
ExcelData sheet1 = new ExcelData(ExcelPAth, name);
//获取第二行第4列
File f = new File(image);
String[] list = f.list();
for (int i = 0; i < 100; i++) {
// String cell2 = sheet1.getExcelDateByIndex(1, 3);
String id = sheet1.getExcelDateByIndex(i, studenId);//第一个行,第二个列
String studentname = sheet1.getExcelDateByIndex(i, St_name);//第一个行,第二个列
for (String s : list) {
//获取某一图片
if (s.equals(studentname+".jpg")||s.equals(studentname+".png")) {
File imagename = new File(image+"\\" + s);
boolean flag= imagename.renameTo(new File(image+"\\" +id+"_"+studentname+ ".jpg"));
System.out.println("修改"+studentname+"的照片"+"是否成功"+flag);
System.out.println("已修改"+id+"_"+studentname+ ".jpg");
}
}
}
}
}