依赖jar包
maven工程可以直接将下面两个依赖拿走,不谢!
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
编写操作excel的工具类
public class ExcelUtil {
private static final String XLS = ".xls";
private static final String XLSX = ".xlsx";
/**
*
* 读取excel文件转化为List<Map<String, Object>>集合
*
* @param suffix 文件后缀
* @param is 文件转化的输入流
* @return List<Map<String, Object>>
*/
public static List<Map<String, Object>> readExcel(String suffix, InputStream is) {
try {
// 判断后缀名和输入流是否为空
if(suffix == null || "".equals(suffix) || is == null) {
return null;
}
// 创建excel对象
Workbook book = null;
if(XLS.equals(suffix)) {
book = new HSSFWorkbook(is);
} else if (XLSX.equals(suffix)) {
book = new XSSFWorkbook(is);
}
// 创建返回值集合
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// 获取第一个sheet对象
Sheet sheet = book.getSheetAt(0);
// 获取最后一行的行号
int lastRowNum = sheet.getLastRowNum();
// 标题数组
String[] titles = null;
// 循环获取行
for(int i = 0; i <= lastRowNum; i++) {
// 获取行对象
Row row = sheet.getRow(i);
Map<String, Object> map = new HashMap<String, Object>();
// 获取最后一列列号
int lastCellNum = row.getLastCellNum();
// 循环获取列
for(int j = 0; j < lastCellNum; j++) {
// 单元格对象
Cell cell = row.getCell(j);
// 单元格数据
String val = cell.getStringCellValue();
// 标题
if(i == 0) {
if(titles == null) {
titles = new String[lastCellNum];
}
// 标题存放到标题数组
titles[j] = val;
}
// 数据
map.put(titles[j], val);
}
// 标题行跳过,不作为数据
if(i == 0) {
continue;
}
// 将数据存入集合
list.add(map);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param sheetName sheet名
* @param suffix 后缀名
* @param dataList 数据集合
* @return Workbook
*/
public static Workbook createExcel(String sheetName, String suffix, List<Map<String, Object>> dataList) {
// 判断基本参数
if(sheetName == null || "".equals(sheetName) ||
suffix == null || "".equals(suffix) ||
dataList == null || dataList.size() == 0) {
return null;
}
// 创建excel对象
Workbook book = null;
if(XLS.equals(suffix)) {
book = new HSSFWorkbook();
} else if (XLSX.equals(suffix)) {
book = new XSSFWorkbook();
}
// 创建sheet
Sheet sheet = book.createSheet(sheetName);
int r = 0;
for(int i = 0; i < dataList.size(); ) {
// 数据
Map<String, Object> data = dataList.get(i);
// 创建行
Row row = sheet.createRow(r);
Set<String> titles = data.keySet();
int j = 0;
for(String title : titles) {
// 创建单元格
Cell cell = row.createCell(j++);
// 给单元格赋值
if(r == 0) {
cell.setCellValue(title);
} else {
cell.setCellValue(data.get(title) + "");
}
}
if(r != 0) {
i++;
}
r++;
}
return book;
}
}
在springMVC配置文件中配置上传文件所需要的解析器
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的编码格式 -->
<property name="defaultEncoding" value="UTF-8"/>
<!--
设置上传文件的大小 单位是字节数
-1代表不限制上传文件大小
-->
<property name="maxUploadSize" value="-1"/>
</bean>
编写controller
上传文件时必须在方法的参数中添加【MultipartFile】
@RequestMapping(value="/import", method= {RequestMethod.POST})
public void importExcel(MultipartFile file) throws Exception {
// 文件名
String filename = file.getOriginalFilename();
// 后缀名
String suffix = filename.substring(filename.lastIndexOf("."));
// 输入流
InputStream is = file.getInputStream();
// 读excel
List<Map<String, Object>> list = ExcelUtil.readExcel(suffix, is);
System.out.println(list);
}
@RequestMapping(value="/export", method= {RequestMethod.GET, RequestMethod.POST})
public void exportExcel(HttpServletResponse response) throws Exception {
// 文件名
String filename = "userInf";
// 后缀名
String suffix = ".xlsx";
// sheetName
String sheetName = "userInfo";
List<Map<String, Object>> list = studentService.queryForList(null);
// 读excel
Workbook excel = ExcelUtil.createExcel(sheetName, suffix, list);
// OutputStream out = new FileOutputStream(new File("D://"+ filename + suffix));
response.setHeader("content-disposition", "attachment;filename=" + filename + suffix);
ServletOutputStream out = response.getOutputStream();
excel.write(out);
out.flush();
out.close();
}
jsp页面
上传文件时要求form表单中
必须添加属性【enctype=“multipart/form-data”】
提交方式必须是【method=“post”】
<form action="stuC/import" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="导入">
</form>
测试
浏览器输入地址开始测试
数据库数据:
excel效果(这里没有做颜色等设置,有点苍白)
个人愚见:
一个人有一千种操作excel的习惯,变数太多,不可能面面俱到,所以工具类编写过程也是指定规则的过程。想用我的功能就必须按照我的规矩来,否则分分钟让你享受蓝屏的刺激。
所以要求excel的单元格格式必须设置为文本类型,需要时可以在插入数据库时做转换即可。
以上内容纯属个人愚见,如有问题,请不吝赐教!!