(1)导入Excel
org.apache.poi
poi
3.14
org.apache.poi
poi-ooxml
3.14
POI结构
HSSF --> xls
XSSF --> xlsx
(1)工作簿 (XSSFWorkbook/HSSFWorkbook)
(2)sheet (XSSFSheet/HSSFSheet)
(3)行(Row)
(4)列(Cell)
(5)数据
从Excel中读取数据,写入数据库
@Test
public void readExcel() throws Exception{
String filePath = “C:\Users\Windows\Desktop\Hello.xlsx”;
//MultipartFile InputStream getInputStream() throws IOException;
//根据文件获取工作簿
XSSFWorkbook workbook = new XSSFWorkbook(new File(filePath));
//获取sheet
XSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
//循环获取所有的行
String name = row.getCell(0).getStringCellValue();
double age = row.getCell(1).getNumericCellValue();
System.out.println(“姓名为:”+name+";年龄为:"+age);
}
workbook.close();
}
@Test
public void readExcel2() throws Exception{
String name = “”;
double age = 0;
String filePath = “C:\Users\Windows\Desktop\Hello.xlsx”;
XSSFWorkbook workbook = new XSSFWorkbook(new File(filePath));
XSSFSheet sheet = workbook.getSheetAt(0);
int rowNum = sheet.getLastRowNum(); //获取的是最后的行号
for(int i = 0 ; i <= rowNum; i++){
XSSFRow row = sheet.getRow(i);
short cellNum = row.getLastCellNum(); //获取最后的单元格号
for(int j = 0 ; j < cellNum; j++){
XSSFCell cell = row.getCell(j);
int cellType = cell.getCellType();//获取单元格的数据类型
if(cellType== Cell.CELL_TYPE_STRING){
name = cell.getStringCellValue();
}
if(cellType==Cell.CELL_TYPE_NUMERIC){
age = cell.getNumericCellValue();
}
}
System.out.println(“姓名为:”+name+";年龄为:"+age);
}
}
从数据库中取出数据,写入Excel
查询数据,List
//1.创建一个工作簿 xls HSSFWorkbook xlsx XSSFWorkbook
//2.创建一个sheet
//3.创建一个row
//4.创建一个单元格
//5.往单元格中写入数据
@Test
public void testWriteExcel() throws Exception{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(“传智播客”);
XSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue(“姓名”);
header.createCell(1).setCellValue(“地址”);
header.createCell(2).setCellValue(“年龄”);
//查询数据库获取数据
List<User> users = new ArrayList<User>();
for(int i = 0 ; i <users.size();i++){
XSSFRow content = sheet.createRow(i+1);
User user = users.get(i);
content.createCell(0).setCellValue(user.getUsername());
content.createCell(1).setCellValue("陕西省西安市");
content.createCell(2).setCellValue(18);
}
FileOutputStream out = new FileOutputStream("C:\\Users\\Windows\\Desktop\\测试.xlsx");
workbook.write(out);
out.close();
workbook.close();
}
实现:
通过Excel将数据导入到数据库中,实现预约设置功能模块。