Java Excel 操作
pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
操作
import com.npy.computer.student.model.Student;
import com.npy.computer.student.service.StudentService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@RestController
public class ExcalImport {
@Autowired
private StudentService studentService;
public void readExcel(File file) throws Exception {
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
Workbook wb = null;
wb = new HSSFWorkbook(inputStream);
Sheet sheet = wb.getSheetAt(0);
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row != null) {
Student student = new Student();
Cell cell = row.getCell(0);
student.setStudentId(cell.toString());
cell = row.getCell(1);
student.setStudentName(cell.toString());
cell = row.getCell(2);
student.setGender(cell.toString());
cell = row.getCell(3);
student.setBorn(cell.toString());
cell = row.getCell(4);
student.setNation(cell.toString());
cell = row.getCell(5);
student.setBirthPlace(cell.toString());
cell = row.getCell(6);
student.setLive(cell.toString());
display(student);
}
}
}
public void display(Student student) {
System.out.println("excel display: "
+ student.getStudentId() + " "
+ student.getStudentName() + " "
+ student.getGender() + " "
+ student.getBorn() + " "
+ student.getNation() + " "
+ student.getBirthPlace() + " "
+ student.getLive() + " ");
}
public void make() throws Exception {
File file = new File("文件所在位置");
readExcel(file);
System.out.println("finish");
}
}