Изображение не вставляется в БД из Excel в Java загрузки весной? - PullRequest
0 голосов
/ 02 февраля 2019

Привет всем Я новичок в Java Spring Boot. Я хочу читать данные из Excel. Данные содержат текст и изображение . У меня есть чтение текста из Excel и Вставить в БД успешно. Но я не смог прочитать изображение, и мне пришлось вставить изображение в БД. Я прикрепил ошибку ниже. Кто-нибудь может дать мне решение?Любая помощь будет признательна. Спасибо заранее ....

Изображение: enter image description here

enter image description here

    @RequestMapping("uploadQuestion")
    public String uploadQuestion(@RequestParam("file") MultipartFile file, @RequestParam Long examId, Model model,
            HttpSession session) throws IOException, InvalidFormatException {
        int flag = 0;
        String id = (String) session.getAttribute("userId");
        model.addAttribute("examList", onlineExamMasterRepository.findAll());
        DataFormatter formatter = new DataFormatter();
        List<OnlineExamQuestionMaster> quetions = new ArrayList<OnlineExamQuestionMaster>();
        List<OnlineExamOptionMaster> options = new ArrayList<OnlineExamOptionMaster>();
        if (file.isEmpty()) {
            model.addAttribute("info", "Please select a file to upload");
            return "onlinexam/questionUpload :: section";
        }
        InputStream in = file.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row row;
        System.out.println(sheet.getLastRowNum());
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            OnlineExamQuestionMaster qm = new OnlineExamQuestionMaster();
            OnlineExamQuestionMasterPK qmp = new OnlineExamQuestionMasterPK();
            OnlineExamOptionMasterPK omp[] = new OnlineExamOptionMasterPK[4];
            OnlineExamOptionMaster om[] = new OnlineExamOptionMaster[4];
            qmp.setExamId(examId);
            qm.setLogTimestamp(new Date());
            qm.setLogUserid(id);

            flag++;
            row = (Row) sheet.getRow(i);
            System.out.println(row.getCell(0).toString());
            if (row.getCell(0).toString().equals(null)) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {

                qmp.setQuestionId(Long.parseLong(formatter.formatCellValue(row.getCell(0))));

                if (onlineExamQuestionMasterRepository.exists(qmp)) {
                    model.addAttribute("message", "Already QuestionId with " + formatter.formatCellValue(row.getCell(0))
                            + " Exist for ExamId " + examId);
                    return "onlinexam/questionUpload :: section";
                }
            }
            if (row.getCell(1).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else 
            {
                row = (Row) sheet.getRow(i);
                Iterator<Cell> iterator2 = row.cellIterator();
                /*XSSFWorkbook workbook2 = sheet.getWorkbook();
                List<XSSFPictureData> pictures = workbook2.getAllPictures();
                Iterator<XSSFPictureData> iterator = pictures.iterator();*/
                while(iterator2.hasNext())
                {
                    PictureData pictureData = (PictureData)iterator2.next();
                    String fileextension = pictureData.suggestFileExtension();
                    byte[] data = pictureData.getData();
                    if(fileextension.equals("jpeg"))
                    {
                        qm.setImage(data);;
                    }
                    else
                        qm.setQidDescription(row.getCell(1).toString().trim());
                }

            }
            if (row.getCell(2).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {

                omp[0] = new OnlineExamOptionMasterPK();
                om[0] = new OnlineExamOptionMaster();
                omp[0].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
                omp[0].setOptionId("A");
                omp[0].setExamId(examId);
                om[0].setLogTimestamp(new Date());
                om[0].setLogUserid(id);
                om[0].setOptionDesc(row.getCell(2).toString().trim());
                om[0].setId(omp[0]);
            }
            if (row.getCell(3).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {
                omp[1] = new OnlineExamOptionMasterPK();
                om[1] = new OnlineExamOptionMaster();
                omp[1].setExamId(examId);
                omp[1].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
                omp[1].setOptionId("B");
                om[0].setLogTimestamp(new Date());
                om[0].setLogUserid(id);
                om[1].setOptionDesc(row.getCell(3).toString().trim());
                om[1].setId(omp[1]);
            }
            if (row.getCell(4).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {
                omp[2] = new OnlineExamOptionMasterPK();
                om[2] = new OnlineExamOptionMaster();
                omp[2].setExamId(examId);
                omp[2].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
                omp[2].setOptionId("C");
                om[0].setLogTimestamp(new Date());
                om[0].setLogUserid(id);
                om[2].setOptionDesc(row.getCell(4).toString().trim());
                om[2].setId(omp[2]);
            }
            if (row.getCell(5).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {
                omp[3] = new OnlineExamOptionMasterPK();
                om[3] = new OnlineExamOptionMaster();
                omp[3].setExamId(examId);
                omp[3].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
                omp[3].setOptionId("D");
                om[0].setLogTimestamp(new Date());
                om[0].setLogUserid(id);
                om[3].setOptionDesc(row.getCell(5).toString().trim());
                om[3].setId(omp[3]);
            }
            if (row.getCell(6).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {
                qm.setAnswer(row.getCell(6).toString().toUpperCase().trim());
            }
            if (row.getCell(7).toString().equals("")) {
                model.addAttribute("info", "Some columns are null please check and try");
                return "onlinexam/questionUpload :: section";
            } else {
                qm.setMarks(Long.parseLong(formatter.formatCellValue(row.getCell(7))));
            }
            qm.setId(qmp);
            quetions.add(qm);
            options.addAll(Arrays.asList(om));

        }

        for (OnlineExamQuestionMaster h : quetions) {
            onlineExamQuestionMasterRepository.save(h);

        }
        System.out.println(options.size());
        for (OnlineExamOptionMaster h : options) {
            System.out.println(h.toString());
            onlineExamOptionMasterRepository.save(h);
        }
        model.addAttribute("info", flag + "Questions Uploaded Sucessfully");
        return "onlinexam/questionUpload :: section";
    }

] 3 ] 3

1 Ответ

0 голосов
/ 02 февраля 2019

Изображения не являются ячейками в Excel.Они находятся в отдельном слое рисования ( XSSFDrawing в случае XSSF) над листом и привязываются к ячейкам.

Таким образом, если необходимо получить изображения в соответствии с положением, к которому они привязаны, то нам нужно

  1. получить слой рисования
  2. для всех фигур вэтот слой, и если форма представляет собой изображение, то
  3. получит изображение
  4. получит позицию привязки этого изображения

Следующий пример делает это и создаетMap, который отображает XSSFPicture на свои позиции.Я получил XSSFPicture , потому что они предоставляют гораздо больше информации, чем один XSSFPictureDataXSSFPictureData можно легко получить из XSSFPicture.

import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.util.Map;
import java.util.HashMap;

public class ExcelGetPicturesWithPosition {

 static Map<String, XSSFPicture> getPicturesWithPosition(XSSFSheet sheet) {
  Map<String, XSSFPicture> pictures = new HashMap<String, XSSFPicture>();
  XSSFDrawing drawing = sheet.getDrawingPatriarch();
  for (XSSFShape shape : drawing.getShapes()) {
   if (shape instanceof XSSFPicture) {
    XSSFPicture picture = (XSSFPicture)shape;
    XSSFClientAnchor anchor = picture.getClientAnchor();
    String cellAddr = "R" + anchor.getRow1() + "C" + anchor.getCol1();
    pictures.put(cellAddr, picture);
   }
  }
  return pictures;
 }

 public static void main(String[] args) throws Exception {
  XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelWithPictures.xlsx"));
  XSSFSheet sheet = workbook.getSheetAt(0);

  Map<String, XSSFPicture> pictures = getPicturesWithPosition(sheet);

  System.out.println(pictures);

  workbook.close();
 }
}

Получив эту Карту, вы легко сможете получить изображения во время итерации листа.Например, если мы находимся на int row = 2; int column = 1;:

XSSFPicture picture = pictures.get("R"+row+"C"+column);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...