1. 程式人生 > >java使用POI 讀取excel2010檔案 並存入oracle資料庫

java使用POI 讀取excel2010檔案 並存入oracle資料庫

首先將使用到的資料庫操作封裝起來

import java.sql.*;

public class DB {
	// 單例模式
	/*
	 * 單例模式是一種常用的軟體設計模式。在它的核心結構中只包含一個被稱為單例類的特殊類。
	 * 通過單例模式可以保證系統中一個類只有一個例項而且該例項易於外界訪問,從而方便對例項個數的控制並節約系統資源。
	 * 如果希望在系統中某個類的物件只能存在一個,單例模式是最好的解決方案。
	 */
	private static DB db;// 保證整個系統中只存在DB的一個物件db

	static {// 當使用該類時首先執行static中的語句
		try {
			Class.forName("oracle.jdbc.OracleDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private DB() {
	}// 單例模式不允許其他類建立物件

	public static Connection getConn() {
		Connection conn = null;
		String url = "jdbc:oracle:thin:@10.218.49.217:1521:KTSC";
		// 資料庫連線,oracle代表連結的是oracle資料庫;thin:@10.218.49.217代表的是資料庫所在的IP地址;
		// 1521代表連結資料庫的埠號;KTSC代表的是資料庫名稱
		String UserName = "A1";// 資料庫使用者登陸名
		String Password = "!qazjkwsx";// 密碼
		try {
			conn = DriverManager.getConnection(url, UserName, Password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	public static void closeConn(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static PreparedStatement getPstmt(Connection conn, String sql) {
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return pstmt;
	}

	public static void closePstmt(PreparedStatement pstmt) {
		try {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

讀取指定路徑資料夾下的所有.xsl檔案 並將其內容讀取出來  新增到資料庫 這裡用到的是POI 3.9的jar包

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

	public static void main(String[] args) {
		Connection conn = DB.getConn();
		Test test = new Test();
		String filepath = "F:\\sj work\\test"; //資料夾路徑 
		try {
			test.readfile(filepath, conn);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			DB.closeConn(conn);
		}
	}

	/**
	 * 讀取某個資料夾下的所有檔案
	 */
	public void readfile(String filepath, Connection conn)
			throws FileNotFoundException, IOException {

		File file = new File(filepath);
		if (file.isDirectory()) {
			System.out.println("資料夾");
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + "\\" + filelist[i]);
				if (!readfile.isDirectory()) {
					System.out.println("path=" + readfile.getPath());
					System.out.println("absolutepath="
							+ readfile.getAbsolutePath());
					System.out.println("name=" + readfile.getName());
					excelToOracle(conn, readfile);
				}
			}
		}
	}

	public void excelToOracle(Connection conn, File file) {
		//假設資料庫表中有4個欄位username,password,phone,addr
		String username = "";
		String password = "";
		String phone = "";
		String addr = "";
		String sql = "insert into test values (?,?,?,?)";
		PreparedStatement pstmt = DB.getPstmt(conn, sql);
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(file));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		XSSFWorkbook workbook = null;
		try {
			workbook = new XSSFWorkbook(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		XSSFSheet sheet = workbook.getSheetAt(0);

		for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
			XSSFRow row = sheet.getRow(rowIndex);
			if (row == null) {
				continue;
			}
			XSSFCell cell = null;
			for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
				String value = "";
				cell = row.getCell(columnIndex);
				if (cell != null) {
					// 注意:一定要設成這個,否則可能會出現亂碼
					// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
					switch (cell.getCellType()) {
					case XSSFCell.CELL_TYPE_STRING:
						value = cell.getStringCellValue();
						break;
					case XSSFCell.CELL_TYPE_NUMERIC:
						if (HSSFDateUtil.isCellDateFormatted(cell)) {
							Date date = cell.getDateCellValue();
							if (date != null) {
								value = new SimpleDateFormat("yyyy-MM-dd")
										.format(date);
							} else {
								value = "";
							}
						} else {
							value = new DecimalFormat("0").format(cell
									.getNumericCellValue());
						}
						break;
					case XSSFCell.CELL_TYPE_FORMULA:
						// 匯入時如果為公式生成的資料則無值
						if (!cell.getStringCellValue().equals("")) {
							value = cell.getStringCellValue();
						} else {
							value = cell.getNumericCellValue() + "";
						}
						break;
					case XSSFCell.CELL_TYPE_BLANK:
						break;
					case XSSFCell.CELL_TYPE_ERROR:
						value = "";
						break;
					case XSSFCell.CELL_TYPE_BOOLEAN:
						value = (cell.getBooleanCellValue() == true ? "Y" : "N");
						break;
					default:
						value = "";
					}
				}
				if (columnIndex == 0 && value.trim().equals("")) {
					break;
				}
				//excel表格中欄位順序為:使用者名稱,密碼,電話和地址,為方便起見假設欄位一一對應
				if (columnIndex == 0) {
					username = value;
				} else if (columnIndex == 1) {
					password = value;
				} else if (columnIndex == 2) {
					phone = value;
				} else if (columnIndex == 3) {
					addr = value;
				}
				System.out.println(value);
			}

			try {
				pstmt.setString(1, username);
				pstmt.setString(2, password);
				pstmt.setString(3, phone);
				pstmt.setString(4, addr);
				pstmt.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		DB.closePstmt(pstmt);
	}
}