1. 環境要求
本文環境爲: 數據庫爲oracle,jdk爲jdk7,依賴jar包爲ojdbc6-11.2.0.4.0.jar+poi-3.14.jar
2.POI 使用
1. 創建工做空間
2. 獲取sheet
3. 使用row
4. 使用cell
3. 代碼部分一
3.1 使用方法導出,代碼以下
private static void test1() {
Connection con=null;
PreparedStatement preStatement=null;
ResultSet result=null;
try{
/**
* 數據庫鏈接
*/
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("開始嘗試鏈接數據庫!");
String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:localOracle";
String user = "hsm";
String password = "1994713";
con = DriverManager.getConnection(url, user, password);
System.out.println("鏈接成功!開始查詢數據");
/**
* 執行sql語句,將結果保存在result中
*/
String sql = "select dict_type,dict_value,dict_desc from frp_dict ";
preStatement = con.prepareStatement(sql);
result = preStatement.executeQuery();
/**
* 建立excel頭
*/
List<String> headers=new ArrayList<String>();
headers.add("dict_type");
headers.add("dict_value");
headers.add("dict_desc");
//建立新工做簿
HSSFWorkbook workbook = new HSSFWorkbook();
//新建工做表
HSSFSheet sheet = workbook.createSheet("frp_dict");
//建立行,行號做爲參數傳遞給createRow()方法,第一行從0開始計算
HSSFRow row = sheet.createRow(0);
for(int i=0;i<headers.size();i++){
HSSFCell cell=row.createCell(i);
cell.setCellValue(headers.get(i));
}
int rowTemp=1;
while(result.next()){
row = sheet.createRow(rowTemp);
for(int i=0;i<headers.size();i++){
HSSFCell cell=row.createCell(i);
cell.setCellValue(result.getString(headers.get(i)));
}
rowTemp++;
}
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\hsm\\Desktop\\exportTest.xls"));
workbook.write(fos);
workbook.close();
fos.close();
}catch (Exception e){
e.printStackTrace();
}finally{
try{
// 逐一將上面的幾個對象關閉,由於不關閉的話會影響性能、而且佔用資源
// 注意關閉的順序,最後使用的最早關閉
if (result != null)
result.close();
if (preStatement != null)
preStatement.close();
if (con != null)
con.close();
System.out.println("數據庫鏈接已關閉!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
3.2 導出結果展現

4 代碼部分二
4.1 調用方法導入,方法以下
private static void test3(){
Connection con=null;
PreparedStatement preStatement=null;
ResultSet result=null;
try{
/**
* 數據庫鏈接
*/
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("開始嘗試鏈接數據庫!");
String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:localOracle";
String user = "hsm";
String password = "1994713";
con = DriverManager.getConnection(url, user, password);
System.out.println("鏈接成功!開始查詢數據");
/**
* 執行sql語句,將結果保存在result中
*/
String sql = "";
FileInputStream fis = new FileInputStream(new File("C:\\Users\\hsm\\Desktop\\exportTest2.xls"));
//建立新工做簿
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//獲取第一個sheet
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row=sheet.getRow(0);
StringBuffer columns=new StringBuffer(row.getCell(0).getStringCellValue());
StringBuffer param=new StringBuffer("?");
for(int i=1;i<row.getLastCellNum();i++){
columns.append(",").append(row.getCell(i).getStringCellValue());
param.append(",").append("?");
}
System.out.println(columns.toString());
sql="insert into frp_dict_test ("+columns+") values ("+param+")";
preStatement = con.prepareStatement(sql);
for(int i=1;i<sheet.getLastRowNum();i++){
row=sheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++){
preStatement.setString(j+1, row.getCell(j).getStringCellValue());
}
preStatement.addBatch();;
if(i%100==0){
preStatement.executeBatch();
}
}
preStatement.executeBatch();
con.commit();
fis.close();
workbook.close();
}catch (Exception e){
e.printStackTrace();
}finally{
try{
// 逐一將上面的幾個對象關閉,由於不關閉的話會影響性能、而且佔用資源
// 注意關閉的順序,最後使用的最早關閉
if (result != null)
result.close();
if (preStatement != null)
preStatement.close();
if (con != null)
con.close();
System.out.println("數據庫鏈接已關閉!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
4.2 導入結果顯示

5.代碼優化,造成工具類
5.1源代碼
package com.hsm.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
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;
/**
* @author hsm
* excel相關的操做
*/
public class ExcelUtil {
private String driverType=null;
private String url=null;
private String userName=null;
private String password=null;
private ExcelUtil(){
}
/**
* 獲取excel的實例
* @param driverType數據庫類型
* @param url 數據庫地址
* @param userName 用戶名
* @param password 密碼
* @return 當前實例
*/
public static ExcelUtil getInstance(String driverType,String url,String userName,String password){
ExcelUtil excelUtil=new ExcelUtil();
excelUtil.driverType=driverType;
excelUtil.url=url;
excelUtil.userName=userName;
excelUtil.password=password;
return excelUtil;
}
/**
* 下載excel<br/>
* 從數據庫中導出相應表相關的字段的excel表格
* @param param 表格頭部內容
* @param tableName 表名
* @param file 文件位置及文件名
*/
public void downloadSqlPara(List<String> param,String tableName,String file){
Connection con=null;
PreparedStatement preStatement=null;
ResultSet result=null;
try{
/**
* 數據庫鏈接
*/
Class.forName(this.driverType);
System.out.println("================開始嘗試鏈接數據庫!===================");
String url = this.url;
String user = this.userName;
String password = this.password;
con = DriverManager.getConnection(url, user, password);
System.out.println("=================鏈接成功!開始查詢數據================");
/**
* 執行sql語句,將結果保存在result中
*/
StringBuffer buffer=new StringBuffer(param.get(0));
for(int i=1;i<param.size();i++){
buffer.append(",").append(param.get(i));
}
String sql = "select "+buffer+" from "+tableName;
preStatement = con.prepareStatement(sql);
result = preStatement.executeQuery();
/**
* 建立excel工做區
*/
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(tableName);
HSSFRow row = sheet.createRow(0);
for(int i=0;i<param.size();i++){
HSSFCell cell=row.createCell(i);
cell.setCellValue(param.get(i));
}
int rowTemp=1;
System.out.println("================開始寫入文件!===================");
while(result.next()){
row = sheet.createRow(rowTemp);
for(int i=0;i<param.size();i++){
HSSFCell cell=row.createCell(i);
cell.setCellValue(result.getString(param.get(i)));
}
rowTemp++;
}
System.out.println("================文件寫入結束!===================");
FileOutputStream fos = new FileOutputStream(new File(file));
workbook.write(fos);
workbook.close();
fos.close();
}catch (Exception e){
e.printStackTrace();
}finally{
try{
// 逐一將上面的幾個對象關閉,由於不關閉的話會影響性能、而且佔用資源
// 注意關閉的順序,最後使用的最早關閉
if (result != null)
result.close();
if (preStatement != null)
preStatement.close();
if (con != null)
con.close();
System.out.println("數據庫鏈接已關閉!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 導入excel表格內容
* @param headers
* @param tableName
* @param file
*/
public void importSqlExcel(List<String> headers,String tableName,String file){
Connection con=null;
PreparedStatement preStatement=null;
ResultSet result=null;
try{
/**
* 數據庫鏈接
*/
Class.forName(this.driverType);
System.out.println("開始嘗試鏈接數據庫!");
String url = this.url;
String user = this.userName;
String password = this.password;
con = DriverManager.getConnection(url, user, password);
System.out.println("鏈接成功!開始查詢數據");
/**
* 打開文件
*/
FileInputStream fis = new FileInputStream(new File(file));
/**
* 建立excel工做區
*/
//建立新工做簿
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row=sheet.getRow(0);
/**
* 獲取excel傳入的字段,並對sql進行初始化
*/
StringBuffer columns=new StringBuffer(row.getCell(0).getStringCellValue());
StringBuffer param=new StringBuffer("?");
for(int i=1;i<row.getLastCellNum();i++){
columns.append(",").append(row.getCell(i).getStringCellValue());
param.append(",").append("?");
}
String sql = "";
sql="insert into "+tableName+" ("+columns+") values ("+param+")";
preStatement = con.prepareStatement(sql);
/**
* 遍歷sheet中的內容,將內容批量插入數據庫中
*/
for(int i=1;i<sheet.getLastRowNum();i++){
row=sheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++){
preStatement.setString(j+1, row.getCell(j).getStringCellValue());
}
preStatement.addBatch();;
if(i%100==0){
preStatement.executeBatch();
}
}
preStatement.executeBatch();
con.commit();
fis.close();
workbook.close();
}catch (Exception e){
e.printStackTrace();
}finally{
try{
// 逐一將上面的幾個對象關閉,由於不關閉的話會影響性能、而且佔用資源
// 注意關閉的順序,最後使用的最早關閉
if (result != null)
result.close();
if (preStatement != null)
preStatement.close();
if (con != null)
con.close();
System.out.println("數據庫鏈接已關閉!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
5.2優化代碼測試
package com.hsm.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
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 com.hsm.util.ExcelUtil;
public class TestMain {
public static void main(String[] args) {
test4();
}
private static void test4(){
/**
* 數據庫相關內容
*/
String driverType="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@127.0.0.1:1521:localOracle";
String userName="hsm";
String password="1994713";
ExcelUtil excelUtil=ExcelUtil.getInstance(driverType, url, userName, password);
/**
* excel導入
*/
List<String>param=new ArrayList<String>();
param.add("dict_type");
param.add("dict_value");
param.add("dict_desc");
String file="C:\\Users\\hsm\\Desktop\\exportTest2.xls";
excelUtil.importSqlExcel(param, "frp_dict_test", file);
}
private static void test2(){
/**
* 數據庫相關內容
*/
String driverType="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@127.0.0.1:1521:localOracle";
String userName="hsm";
String password="1994713";
ExcelUtil excelUtil=ExcelUtil.getInstance(driverType, url, userName, password);
/**
* excel下載
*/
List<String>param=new ArrayList<String>();
param.add("dict_type");
param.add("dict_value");
param.add("dict_desc");
String file="C:\\Users\\hsm\\Desktop\\exportTest2.xls";
excelUtil.downloadSqlPara(param, "frp_dict", file);
}
}