반응형

#  Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출 후 Excel에 저장하기

  • Naver Search API 연동, 도서정보를 입력(요청 변수 값) 하여 원하는 정보(ISBN, IMAGE) 검출. (Jsoup 사용)
  • 검출된 데이터 Excel에 저장.

## 작업 소스

  • 메인 java 소스
import java.io.*;

import kr.inflearn.ExcelDAO;

public class Project03_F {
	public static void main(String[] args) {
		ExcelDAO dao = new ExcelDAO();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			System.out.print("입력처리(I) / 종료(E) : ");
			String sw = br.readLine();
			switch (sw) {
				case "I":
					dao.excel_input();
					break;
				case "E":
					System.out.println("프로그램이 종료됩니다.");
					System.exit(0);
					break;
				default:
					System.out.println("I or E 를 입력해주세요.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 실 기능 수행하는 java 소스
package kr.inflearn;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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 org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class ExcelDAO {
	private List<ExcelVO> list;
	private HSSFWorkbook wb;
	public ExcelDAO() {
		list = new ArrayList<ExcelVO>();
		wb = new HSSFWorkbook();
	}
	
	public void excel_input() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			HSSFSheet firstSheet = wb.createSheet("BOOK SHEET");
			HSSFRow rowA = firstSheet.createRow(0);
			HSSFCell cellA = rowA.createCell(0);
			cellA.setCellValue(new HSSFRichTextString("책제목"));
			
			HSSFCell cellB = rowA.createCell(1);
			cellB.setCellValue(new HSSFRichTextString("저자"));
			
			HSSFCell cellC = rowA.createCell(2);
			cellC.setCellValue(new HSSFRichTextString("출판사"));
			
			HSSFCell cellD = rowA.createCell(3);
			cellD.setCellValue(new HSSFRichTextString("ISBN"));

			HSSFCell cellE = rowA.createCell(4);
			cellE.setCellValue(new HSSFRichTextString("이미지이름"));
			
			int i = 1;
			while (true) {
				System.out.print("책의 제목을 입력해주세요 : ");
				String title = br.readLine();
				System.out.print("책의 저자를 입력해주세요 : ");
				String author = br.readLine();
				System.out.print("책의 출판사를 입력해주세요 : ");
				String company = br.readLine();
				
				HSSFRow rowRa1 = firstSheet.createRow(i);
				HSSFCell cellTitle = rowRa1.createCell(0);
				cellTitle.setCellValue(new HSSFRichTextString(title));
				HSSFCell cellAuthor = rowRa1.createCell(1);
				cellTitle.setCellValue(new HSSFRichTextString(author));
				HSSFCell cellCompany = rowRa1.createCell(2);
				cellTitle.setCellValue(new HSSFRichTextString(company));
				i++;
				
				ExcelVO vo = new ExcelVO(title, author, company);
				ExcelVO data = naver_search(vo);
				list.add(data);
				System.out.println("계속 입력하시려면 Y / 종료하시려면 N 을 입력해주세요 : ");
				String key = br.readLine();
				if (key.equals("N")) break;
			}
			System.out.println("데이터 추출 작업 중 입니다.........");
			excel_save();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ExcelVO naver_search(ExcelVO vo) {
		try {
			String openApi = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl=" 
					+ URLEncoder.encode(vo.getTitle(), "UTF-8") 
					+ "&d_auth=" + URLEncoder.encode(vo.getAuthor(), "UTF-8") 
					+ "&d_publ="+ URLEncoder.encode(vo.getCompany(), "UTF-8");
			
			URL url = new URL(openApi);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-Naver-Client-Id", "발급받은 Client_Id 입력");
			con.setRequestProperty("X-Naver-Client-Secret", "발급받은 Client_Secret 입력");
			
			int responseCode = con.getResponseCode();
			BufferedReader br1 = null;

			if (responseCode == 200) {
				br1 = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			} else {
				br1 = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			
			String inputLine = null;
			StringBuffer response = new StringBuffer();
			
			while ((inputLine = br1.readLine()) != null) {
				response.append(inputLine);
			}
			br1.close();
			
			// ISBN, IMAGE 정보 꺼내기
			Document doc = Jsoup.parse(response.toString());
			Element isbn = doc.select("isbn").first();
			String img = doc.toString();
			String imgTag = img.substring(img.indexOf("<img>")+5);
			
			img = imgTag.substring(0, imgTag.indexOf("?"));
			vo.setIsbn(isbn.text().split(" ")[1]);
			
			String fileName = img.substring(img.lastIndexOf("/")+1);
			vo.setImageUrl(fileName);
			
			// DownloadBroker
			Runnable download = new DownloadBroker(img, fileName);
			Thread t = new Thread(download);
			t.start();			
		} catch (Exception e) {
			e.printStackTrace();
		}
			
		return vo;
	}
	
	private void excel_save() {
		try {
			HSSFSheet sheet = wb.getSheetAt(0);
			
			if (wb != null && sheet != null) {
				Iterator rows = sheet.rowIterator();
				rows.next();
				
				int i = 0;
				while (rows.hasNext()) {
					HSSFRow row = (HSSFRow) rows.next();
					HSSFCell cell = row.createCell(3);		
					cell.setCellType(CellType.STRING);
					cell.setCellValue(list.get(i).getIsbn());
					
					cell = row.createCell(4);
					cell.setCellType(CellType.STRING);
					cell.setCellValue(list.get(i).getImageUrl());
					
					InputStream inputStream = new FileInputStream(list.get(i).getImageUrl());
					byte[] bytes = IOUtils.toByteArray(inputStream);
					int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
					inputStream.close();
					
					CreationHelper helper = wb.getCreationHelper();
					Drawing drawing = sheet.createDrawingPatriarch();
					ClientAnchor anchor = helper.createClientAnchor();
					
					anchor.setCol1(5);
					anchor.setRow1(i+1);
					anchor.setCol2(6);
					anchor.setRow2(i+2);
					
					Picture pict = drawing.createPicture(anchor, pictureIdx);
					Cell cellImg = row.createCell(5);
					int widthUnits = 20*256;
					sheet.setColumnWidth(5, widthUnits);
					short heightUnits = 120*20;
					cellImg.getRow().setHeight(heightUnits);
					
					i++;
				}
				
				FileOutputStream fos = new FileOutputStream("isbn.xls");
				wb.write(fos);
				fos.close();
				System.out.println("ISBN 및 ImageURL 저장 성공.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

## 출력 결과

  • 아래와 같이 진행 시 Java의 정석 책 표지 이미지가 추출되어 저장되는것을 확인할 수 있다.

반응형
반응형

#  Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출하기

  • Naver Search API 연동, 도서정보를 입력(요청 변수 값) 하여 원하는 정보(ISBN, IMAGE) 검출. (Jsoup 사용)

## 준비물

 

책 - Search API

책 NAVER Developers - 검색 API 책 검색 개발가이드 검색 > 책 네이버 책 검색 결과를 출력해주는 REST API입니다. 비로그인 오픈 API이므로 GET으로 호출할 때 HTTP Header에 애플리케이션 등록 시 발급받은 C

developers.naver.com

  • 위 사이트 접속하여 '오픈 API 이용 신청' 버튼 클릭.

  • 아래와 같이 정보 입력하여 등록 신청.

  • 등록 완료 시 발급 되는 키 (Client ID, Client Secret) 이용하여 연동 진행.

## 작업 소스

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import kr.inflearn.ExcelVO;

public class Project03_D {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			System.out.print("책의 제목을 입력해주세요 : ");
			String title = br.readLine();
			System.out.print("책의 저자를 입력해주세요 : ");
			String author = br.readLine();
			System.out.print("출판사를 입력해주세요 : ");
			String company = br.readLine();
			
			ExcelVO vo = new ExcelVO(title, author, company);

			getIsbnImage(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void getIsbnImage(ExcelVO vo) {
		try {
			String openApi = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl=" 
					+ URLEncoder.encode(vo.getTitle(), "UTF-8") 
					+ "&d_auth=" + URLEncoder.encode(vo.getAuthor(), "UTF-8") 
					+ "&d_publ="+ URLEncoder.encode(vo.getCompany(), "UTF-8");
			
			URL url = new URL(openApi);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-Naver-Client-Id", "발급받은 Client_Id 입력");
			con.setRequestProperty("X-Naver-Client-Secret", "발급받은 Client_Secret 입력");
			
			int responseCode = con.getResponseCode();
			BufferedReader br1 = null;

			if (responseCode == 200) {
				br1 = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			} else {
				br1 = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			
			String inputLine = null;
			StringBuffer response = new StringBuffer();
			
			while ((inputLine = br1.readLine()) != null) {
				response.append(inputLine);
			}
			br1.close();
			
			// ISBN, IMAGE 정보 꺼내기
			Document doc = Jsoup.parse(response.toString());
			Element total = doc.select("total").first();
			
			if (!total.text().equals("0")) {
				Element isbn = doc.select("isbn").first();
				String isbnStr = isbn.text();
				String isbn_find = isbnStr.split(" ")[1];
				vo.setIsbn(isbn_find);
				
				String imgDoc = doc.toString();
				String imgTag = imgDoc.substring(imgDoc.indexOf("<img>")+5);
				String imgURL = imgTag.substring(0, imgTag.indexOf("?"));
				System.out.println(imgURL);
				String fileName = imgURL.substring(imgURL.lastIndexOf("/")+1);
				System.out.println(fileName);
				vo.setImageUrl(fileName);
				System.out.println(vo);
			} else {
				System.out.println("검색된 데이터가 없습니다.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
}

## 출력 결과

  • 도서 정보 입력 후 확인 시 아래와 같이 출력 되는것을 확인할 수 있다.

 

반응형
반응형

# Naver Search API 활용 Excel에서 Cell의 데이터타입 알아보기

## 작업소스

  • 아래와 같이 엑셀 파일 생성하여 저장.

cellDataType.xls
0.02MB

  • 아래와 같이 작업하여 셀타입 확인 가능.
import java.io.FileInputStream;
import java.util.Iterator;

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 org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

public class Project03_C {
	public static void main(String[] args) {
		String fileName = "cellDataType.xls";
		
		try (FileInputStream fis = new FileInputStream(fileName)) {
			
			HSSFWorkbook workbook = new HSSFWorkbook(fis);
			
			HSSFSheet sheet = workbook.getSheetAt(0);
			Iterator<Row> rows = sheet.rowIterator();
			
			while (rows.hasNext()) {
				HSSFRow row = (HSSFRow) rows.next();
				Iterator<Cell> cells = row.cellIterator();
				
				while (cells.hasNext()) {
					HSSFCell cell = (HSSFCell) cells.next();
					CellType type = cell.getCellType();
					
					if (type == CellType.STRING) {
						System.out.println("[" + cell.getRowIndex() 
								+ "," + cell.getColumnIndex() + "]"
								+ " = STRING; Value : " + cell.getRichStringCellValue());
					} else if (type == CellType.NUMERIC) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = NUMERIC; Value : " + cell.getNumericCellValue());
					} else if (type == CellType.BOOLEAN) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = BOOLEAN; Value : " + cell.getBooleanCellValue());
					} else if (type == CellType.BLANK) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = BLANK; Value : BLANK CELL");
					}					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
반응형
반응형

# Naver Search API 활용 Excel에 image 저장하기

기존에 존재하는 Excel 파일을 읽어 오는게 아닌, 엑셀 파일을 만들고 원하는 위치에 이미지를 넣어 생성하는 방식.준비물 : 엑셀에 삽입할 이미지. (pic.jpg)## 작업소스

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;

public class Project03_B {
	public static void main(String[] args) {
		try {
			Workbook wb = new HSSFWorkbook();
			Sheet sheet = wb.createSheet("sample Excel");	// Excel 시트 생성 및 시트명 입력(sample Excel)
			
			InputStream inputStream = new FileInputStream("pic.jpg"); 		// 이미지 파일 읽기.
			byte[] bytes = IOUtils.toByteArray(inputStream);			// 이미지 파일 byte 단위로 읽어서 저장.
			int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);	// 이미지 번지 저장.
			inputStream.close();
			
			CreationHelper helper = wb.getCreationHelper();		// Workbook에 뭔가를 생성할 수 있도록 하는 헬퍼.
			Drawing drawing = sheet.createDrawingPatriarch();	// 시트에 그림을 그릴수 있도록 해줌.
			ClientAnchor anchor = helper.createClientAnchor();	// 위치 잡기용.
			anchor.setCol1(1);	// Column : B
			anchor.setRow1(2);	// Row : 3
			anchor.setCol2(2);	// Column : C
			anchor.setRow2(3);	// Row : 4
			
			Picture pict = drawing.createPicture(anchor, pictureIdx);	// 위치에 이미지 그리기.
			
			// Cell 생성하여 이미지 크기 설정.
			Cell cell = sheet.createRow(2).createCell(1);
			int widthUnits = 20*256;				// Excel 한 칸을 기준, 하나의 픽셀 데이터가 넓이 1/256 수준.
			sheet.setColumnWidth(1,  widthUnits);		
			short heightUnits = 120*20;				// Excel 한 칸을 기준, 하나의 픽셀 데이터가 1/20 수준.
			cell.getRow().setHeight(heightUnits);
			
			
			// Excel 파일 저장.
			FileOutputStream fileOut = new FileOutputStream("myFile.xls");
			wb.write(fileOut);
			fileOut.close();
			
			System.out.println("성공!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

## 결과물

 

반응형

+ Recent posts