JDBC는 EXCEL 데이터를 데이터베이스에 저장합니다(3.POI는 Excel 데이터를 데이터베이스에 저장합니다).

1. POIjar 파일을 준비합니다. 저는 Poi-3.7-201029.jar
2.java
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;


public class ExcelToDB {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		ExcelToDB db = new ExcelToDB();
		db.excelToDB();
	}
	
	public void excelToDB() throws Exception{
		String filePath = "D:\\student.xls";
		File file  = new File(filePath);
		if(!file.exists() || !file.canRead()){
			System.out.println(" ");
			return;
		}
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
		//  Workbook 
		HSSFWorkbook wb = new HSSFWorkbook(fs);

		// get Sheet 
		Sheet sheet = wb.getSheetAt(0);
		//  
		Row srow = sheet.getRow(1);
		if (srow == null){
			return;
		}
		//  
		int columnLength = 2;
		List<Student> list = new ArrayList<Student>();
		Student stu = null;
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			Row row = sheet.getRow(i);
			stu = new Student();
			ArrayList<String> data = getRowData(row,columnLength);
			
			int k = 0;
			String id = data.get(k++).trim(), name = data.get(k++).trim();
			stu.setId(id);
			stu.setName(name);
			
			list.add(stu);
		}
		saveDatoToDB(list);
	}
	
	/**
	 *  
	 * @param list
	 */
	private void saveDatoToDB(List<Student> list){
		Connection conn = JDBCUtilSingle.getInstance().getConnection();
		try {
			PreparedStatement st= conn.prepareStatement("insert into student(id,name) values(?,?)");
			for(Student stu : list){
				st.setString(1, stu.getId());
				st.setString(2, stu.getName());
				st.addBatch();
			}
			st.executeBatch();
			JDBCUtilSingle.getInstance().closeConnection(null, st, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *  Excel 
	 */
	private ArrayList<String> getRowData(Row row, int len){
		ArrayList<String> data = new ArrayList<String>();
		for(int j=0; j<len; j++){
			Cell c = row.getCell(j);
			String v;
			if(c==null){
				data.add("");
				continue;
			}
			switch(c.getCellType()){
				case Cell.CELL_TYPE_BLANK:
					v = "";
					break;
				default:
					v = c.toString().trim();
					break;
			}
			data.add(v);
		}
		return data;
	}

}

데모 다운로드 주소

좋은 웹페이지 즐겨찾기