1. 程式人生 > >Javaweb----上傳檔案,excle表格錄入資料庫的表中

Javaweb----上傳檔案,excle表格錄入資料庫的表中

上傳檔案,excle表格錄入資料庫的表中

一開始遙望資料庫中錄入測試資料,但由於要做考試系統,所以用到了一個東西,那就是能不能把表格裡的東西錄入到資料庫中呢?經過仔細的研究,終於找到一種方式了。下面來講解一下把。

首先呢,<input>標籤中可以上傳檔案圖片什麼的,必須要用到這個。這裡需要用到SpringMVC、excle錄入資料庫的包。需要匯入一些jar包。先在資料庫中建好一個空表。

新建的web專案,匯入jar包。在src目錄下新建一個包。有這麼些類。

//這個是連結資料庫的類

public class DBConnection {
private static Connection con = null;


// 驅動程式名
private static  String driverName = "com.mysql.jdbc.Driver";
// 資料庫使用者名稱
private static  String userName = "root";
// 密碼
private static  String userPasswd = "ffffff";
// 資料庫名
private static  String dbName = "test";
// 聯結字串
private static  String url = "jdbc:mysql://localhost/" + dbName + "?user="
+ userName + "&password=" + userPasswd
+ "&useUnicode=true&characterEncoding=gbk";


public static  Connection getConnection() {


try {
Class.forName(driverName);
con = DriverManager.getConnection(url);


} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}


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

//這個是實體類,裡面是資料庫的列名
public class Excel {
private String pid;
private String name;
private String num;
private String www;
public Excel(String pid, String name, String num, String www) {
super();
this.pid = pid;
this.name = name;
this.num = num;
this.www = www;
}
public Excel(){}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getWww() {
return www;
}
public void setWww(String www) {
this.www = www;
}

}

//.xlsx檔案用XSSFWorkbook   .xlx 用的HSSFWorkbook      對錶格的讀入

public class TestExcel {
//記錄類的輸出資訊-
Log log=LogFactory.getLog(TestExcel.class);
//獲取Excel文件的路徑-
//.xlsx檔案用XSSFWorkbook   .xlx 用的HSSFWorkbook
//public static String filepath="D://www.xlsx";
public static void start(String path){
//建立對excel工作簿的引用
XSSFWorkbook wookbook;
try {
wookbook = new XSSFWorkbook(new FileInputStream(path));
//在Execl文件中,第一張工作表的預設索引是0
//XSSFSheet sheet=wookbook.getSheetAt(0);
XSSFSheet sheet=wookbook.getSheet("Sheet1");
//獲取到Execl檔案中的所有行數-
int rows=sheet.getPhysicalNumberOfRows();
//遍歷行
for(int i=1;i<rows;i++){
//讀取左上端單元格
XSSFRow row=sheet.getRow(i);
//行不能空
if(row!=null){
//獲取到所有的列-
int cells=row.getPhysicalNumberOfCells();
String value="";
//遍歷列-
for(int j=0;j<cells;j++){
//獲取列的值
XSSFCell cell=row.getCell(j);
if(cell!=null){
switch(cell.getCellType()){
//這個型別是:公式
//Excel裡面的“公式”,可以用cell.getNumericCellValue(); 來獲得“結果”,也就是“公式”計算之後的結果 
case HSSFCell.CELL_TYPE_FORMULA:
break;
//這個型別是:數字
case HSSFCell.CELL_TYPE_NUMERIC:
value+=cell.getNumericCellValue()+",";
break;
case HSSFCell.CELL_TYPE_STRING:
value+=cell.getStringCellValue()+",";
break;
default:
value +=0;
}
}
}
//將資料插入到mysql資料庫中
String[] val=value.split(",");
Excel entity=new Excel();
entity.setPid(val[0]);
entity.setName(val[1]);
entity.setNum(val[2]);
entity.setWww(val[3]);
TestMethod method=new TestMethod();
int a=method.add(entity);
if(a>0){
System.out.println("插入成功");
}else{
System.out.println("插入失敗");
}


}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

//插入到資料庫表中的類

public int add(Excel te){

Connection con = DBConnection.getConnection();
PreparedStatement pstmt = null;
int count = 0;
String sql = " insert into excel(pid,name,num,www) values(?,?,?,?)";
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, te.getPid());
pstmt.setString(2, te.getName());
pstmt.setString(3, te.getNum());
pstmt.setString(4, te.getWww());
count = pstmt.executeUpdate();
/*
* if(count==0){ throw new DataAlreadyExistException(); }
*/
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBConnection.closeConnection();
}
return count;
}


}

//springmvc 的類

@Controller
public class HelloSpringMVC {

//上傳Excel
@RequestMapping("file/upload")
public String upload(HttpSession session,
@RequestParam MultipartFile file)throws IllegalStateException,IOException{
if(!file.isEmpty()){
String location=session.getServletContext().getRealPath("upload");
String path=location+"/"+
System.currentTimeMillis()+file.getOriginalFilename();
System.out.println(path);
file.transferTo(new File(path));
TestExcel.start(path);
}

return "ok";
}
}

//index.jsp中的表單

<form action="file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上傳excle"><br>
  
    </form>

ok.jsp中沒有東西。

ApplicationContext.xml和web.xml檔案中自己配製吧。

這裡面有幾個問題:

1.你自己建的excle表中第一行需要有列名,如果沒有列名第一條會錄不進去,在TestExcel 類中for(int i=1;i<rows;i++)這裡i改成0,就可以了。

2.注意你的電腦中新建的excle表的儲存字尾名,如果是.xlsx檔案用XSSFWorkbook   .xlx 用的HSSFWorkbook,在TestExcel 類中有註釋。