package com.nongyuanbao.farm.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFPictureData; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.neptune.core.project.AutoIdHelper; import com.neptune.file.service.FileHelper; import com.nongyuanbao.farm.model.Crops; public class ReadExcelServer { public void add() throws FileNotFoundException, IOException {
//寻找要导入数据库的Excel的文件 在本地电脑的位置 File excelFile = new File("E:\A3.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(excelFile)); XSSFSheet sheet = wb.getSheetAt(0); // 读取图片 List<XSSFPictureData> pictures = wb.getAllPictures(); // for (Row row : sheet) { for (int i = 0; i < sheet.getLastRowNum(); i++) { // 单元格 // for (Cell cell : row) { //创建一个对象 用于把数据set入对象里 再把对象save添加进数据库
XSSFRow row = sheet.getRow(i);
Crops crops = new Crops()
for (int s = 0; s < row.getLastCellNum(); s++) {
//查看读取的数据内容 Cell cell = row.getCell(s); // } switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(cell.getRichStringCellValue().getString()); //根据s判断它读的是一行内的第几个单元格 //N行的第一个单元格 if (s == 0) { crops.setId(AutoIdHelper.getId()); crops.setFarmName(cell.getRichStringCellValue().getString()); } else if (s == 1) {//N行的第2个单元格 crops.setFarmCrops(cell.getRichStringCellValue().getString()); } else if (s == 2) {//N行的第3个单元格 crops.setGatherTime(cell.getRichStringCellValue().getString()); } else if (s == 3) {//N行的第4个单元格 crops.setNongYuanBaoId(cell.getRichStringCellValue().getString()); } System.out.print("|"); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.print(String.valueOf(cell.getDateCellValue())); } else { System.out.print(cell.getNumericCellValue()); } System.out.print("|"); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue()); System.out.print("|"); break; default: } } //读取图片代码(是一行一行读的) XSSFPictureData pictureData = pictures.get(i); byte[] data = pictureData.getData(); if (data==null) { crops.setImage(null); }else { crops.setImage(new String(Base64.encodeBase64(data))); } System.out.println(new String(Base64.encodeBase64(data))); //把图片和文字添加到数据库 crops.save(); System.out.println(); } System.out.println(wb.getSheetName(0)); renderSuccess("操作成功!!"); } }