读取excel文件并以对象存储
import com.ruoyi.system.domain.Student;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class test3 {
public static void main(String[] args) throws Exception {
List<Student> list = readXls();
for(Student stu : list){
studentMapper.add(stu);
}
}
public static List<Student> readXls() throws Exception {
InputStream is = new FileInputStream("D:/student.xls");
HSSFWorkbook excel = new HSSFWorkbook(is);
Student stu = null;
List<Student> list = new ArrayList<Student>();
// 循环工作表Sheet
for (int numSheet = 0; numSheet < excel.getNumberOfSheets(); numSheet++) {
HSSFSheet sheet = excel.getSheetAt(numSheet);
if (sheet == null)
continue;
// 循环行Row
for (int rowNum = 1; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow row = sheet.getRow(rowNum);
if (row == null)
continue;
stu = new Student();
// 循环列Cell
// 0学号 1姓名 2年龄 3生日
/*System.out.println((int)cell0.getNumericCellValue());
System.out.println(cell1.getStringCellValue());
System.out.println((int)cell2.getNumericCellValue());
System.out.println(cell3.getStringCellValue());*/
/**console:
* 1
name1
2018-12-13
name2
2019-01-01
*/
HSSFCell cell0 = row.getCell(0);
if (cell0 == null)
continue;
stu.setId((int)cell0.getNumericCellValue());
HSSFCell cell1 = row.getCell(1);
if (cell1 == null)
continue;
stu.setName(cell1.getStringCellValue());
HSSFCell cell2 = row.getCell(2);
if (cell2 == null)
continue;
stu.setAge((int)cell2.getNumericCellValue());
HSSFCell cell3 = row.getCell(3);
if (cell3 == null)
continue;
stu.setBirth(cell3.getStringCellValue());
list.add(stu);
}
}
return list;
}
@SuppressWarnings("unused")
private static String getValue(HSSFCell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//返回数值类型
return String.valueOf(cell.getNumericCellValue());
} else {
//返回字符串类型
return cell.getStringCellValue();
}
}
}