package com.lsf;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.sql.*;
import java.io.*;
import java.util.ArrayList;
import java.sql.Connection;
public class ReadExcelTest
{
private Connection con;
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";
String DBDriver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String USER="sa";
String PWD="sa";
private ArrayList listFirstColum = new ArrayList();
private ArrayList listSecondColum = new ArrayList();
// 串連資料庫
public ReadExcelTest() throws Exception
{
try
{
Class.forName(DBDriver);
con=DriverManager.getConnection(url,USER,PWD);
}
catch(Exception e)
{
e.printStackTrace();
throw(new Exception("Sorry,database connecting failed!"));
}
}
// 從excel中讀取資料存入ArrayList中
public void readExcel(String sFileName)
{
try
{
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(sFileName));// 讀取excel檔案
HSSFSheet sheet = workbook.getSheetAt(0);// 讀取第一個sheet
for(int i=0;i<=sheet.getLastRowNum();i++)// 迴圈取得所有行
{
if(sheet.getRow(i)!=null)
{
HSSFRow aRow = sheet.getRow(i);// 行數
HSSFCell cellFirstColum = aRow.getCell((short)0);// 第一列
HSSFCell cellSecondColum = aRow.getCell((short)1);// 第二列
// 把資料存入list裡備用
listFirstColum.add((int)cellFirstColum.getNumericCellValue());// 假定第一列為數字型
listSecondColum.add(cellSecondColum.getStringCellValue());// 假定第二列為字串型
}
}
System.out.println("Excel讀取成功!");
}catch(Exception e)
{
e.printStackTrace();
}
}
// 從ArrayList中把資料寫入資料庫
public void insertData(String sFileName)
{
// 讀取
readExcel(sFileName);
String sqlInsert = "insert into impExcel"
+"(first_colum,second_colum)values(?,?)";
// 插入
try
{
for (int i=0;i<listFirstColum.size();i++){
PreparedStatement pstmt=con.prepareStatement(sqlInsert);
pstmt.setInt(1, Integer.parseInt(listFirstColum.get(i).toString()));
pstmt.setString(2, listSecondColum.get(i).toString());
pstmt.execute();
System.out.println("正在匯入第 "+(i+1)+" 條記錄");
}
System.out.println("匯入完畢!");
}catch(Exception e)
{
e.printStackTrace();
}
}
}