1. 程式人生 > >學習java通過poi上傳excel檔案

學習java通過poi上傳excel檔案

近期接了一個小功能,需要用到excel匯入匯出功能,學習了一下apache的poi技術,現做如下筆記:

傳統的通過form表單提交上傳檔案的寫法:

<form action="XXX" method="post" enctype="multipart/form-data">

    <input type="file" name="xxx.xlsx">

    <input type="submit" value="upload">

</form>

使用ocupload方法:

1、引入相關的js檔案(注意檔案路徑):

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.ocupload-1.1.2.js"></script>

在body中新增一個按鈕: <input id="myButton" type="button" value="上傳">

為按鈕繫結事件:

<script type="text/javascript">
$(function(){
$("#myButton").upload({
action:'xxx.action',
name:'myFile'
});
});

</script>

在服務端接收檔案:在對應的處理的類中建立一個File物件及其set方法。注意前後端的檔名字一樣。excel檔案上傳之後會儲存到tomcat的temp中,可以在後臺列印一下該名字,獲取臨時檔案的地址。

匯入相關依賴:(注意該excel匯入功能使用的是2007版excel)

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
    <groupId>org.lucee</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<dependency>  
    <groupId>org.apache.xmlbeans</groupId>  
    <artifactId>xmlbeans</artifactId>  
    <version>2.6.0</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.commons</groupId>  
    <artifactId>commons-collections4</artifactId>  
    <version>4.1</version>  
</dependency>

解析excel的單元測試部分:

public class POITest {
//使用POI解析Excel檔案
@Test
public void test1() throws FileNotFoundException, IOException{
String filePath = "你的需要解析的excel的檔案的路徑";
StringBuffer sb =new StringBuffer();
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
Sheet sheet = workbook.getSheetAt(0);
//遍歷標籤頁中的所有的行
for (Row row : sheet) {
for (Cell cell : row) {
cell.setCellType(CellType.STRING);
String value = cell.getStringCellValue();
sb.append(value).append(" ");
}
sb.append("\r\n");
}
System.out.println(sb);
}
}

然後即可實現批量匯入excel。