学习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。

猜你喜欢

转载自blog.csdn.net/guojing1173132123/article/details/80537184