智销功能_导入导出
最常用的是下面两种:
jxl:只能对Excel进行操作,属于比较老的框架。
POI:是apache的项目,可对ms的word,Excel,PPT进行操作
需要的jar包
<!-- poi支持的jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
读取Excel
excel文件做测试(99乘法表)
/**
* 读取我们使用相应的方案
* @throws Exception
*/
@Test
public void readExcel() throws Exception{
File file = new File("employee-3.xlsx");
FileInputStream fis = new FileInputStream(file);
//1.读取一个Excel文件(内存中)
Workbook wb = new XSSFWorkbook(fis);
//2.拿到第个sheet表
Sheet sheet = wb.getSheetAt(0);
//3.拿到wb中的行(不要拿头部)
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
//4.拿到每一列(格子)
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
}
导出
jsp添加导出按钮
<a href="路径 " class="easyui-linkbutton" iconCls="icon-redo" plain="true">导出</a>
js加上导出方法
var itsource={
…
//导出数据
export:function(){
$('#searchForm').submit();
}
}
导入
applicationContext-mvc.xml配置
<!-- 上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>1048576</value>
</property>
</bean>
准备上传的页面
%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%@include file="/WEB-INF/views/head.jsp" %>
</head>
<body>
<span style="color: red">${count}</span>
<!-- 上传请配置enctype -->
<form action="/import/xlsx" method="post" enctype="multipart/form-data">
<%--<input type="file" name="xlsxFile" /> --%>
<input class="easyui-filebox" name="xlsxFile" data-options="prompt:'选择一个文件...'" style="width:80%">
<button class="easyui-linkbutton" type="submit">确定</button>
</form>
</body>
</html>
准备上传的工具方法
/**
* 导入功能:传一个文件的输入流,讲取完成后返回一个相应的数据集合
* @throws Exception
*/
public static List<String[]> importExcel(InputStream is) throws Exception{
//一.准备装数据的容器
List<String[]> list = new ArrayList<>();
//1.读取一个Excel文件(内存中)
Workbook wb = new XSSFWorkbook(is);
//2.拿到第个sheet表
Sheet sheet = wb.getSheetAt(0);
//3.拿到wb中的行(不要拿头部)
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
//4.拿到每一列(格子)
short lastCellNum = row.getLastCellNum();
//二.准备一个String[]装一行数据(有几列就有几条数据)
String[] data = new String[lastCellNum];
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
data[j] = cell.getStringCellValue();
}
//三.把一行数据写到集合中去
list.add(data);
}
return list;
}