文章目录
- 前言
- 导出excel
- 导入excel
- 上传文件获取文件名(中文文件名问题)
- xls和xlsx文件的区别
前言
web开发项目,经常会有导出和导出excel文件的需求。如何导出(下载到excel文件)和导入excel(从excel向系统导入数据)?
excel文件的类型有
- .xls
excel 2007之前的格式,包含2007 - .xlsx
excel 2007之后的格式,内存占用更小。 - .csv
该文件可以以txt形式读取,内容之间用英文逗号隔开。
注意:本文只涉及到xls和xlsx文件的导入和导出。csv文件的实质就是txt,所以本文不做介绍。
导出excel
- 添加依赖
<!-- excel导入导出插件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
- 编写excel导出工具类
package com.it2.springbootweb2.util;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.collections.CollectionUtils;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
/**
* Excel导出
*
* @author leng
*/
public class ExcelExportUtils {
/**
* 导出Excel
*
* @param headList Excel表头列表
* @param dataList Excel内容列表
* @param sheetName Excel工作表名称
* @param fileName 文件名
* @param response 响应对象
* @throws IOException
*/
public static void exportExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, String fileName, HttpServletResponse response)
throws IOException {
ServletOutputStream servletOutputStream = null;
try {
servletOutputStream = response.getOutputStream();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
if (null == fileName|| fileName.trim().equals("")) { //如果不设置文件名,则默认
fileName = new String((sheetName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);
}
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
ExcelWriter writer = new ExcelWriter(servletOutputStream, ExcelTypeEnum.XLSX, true);
Sheet sheet = new Sheet(1, 0);
sheet.setSheetName(sheetName);
Table table = new Table(1);
List<List<String>> head = new ArrayList<>();
if (!CollectionUtils.isEmpty(headList)) {
headList.forEach(headName -> head.add(Arrays.asList(headName)));
}
table.setHead(head);
List<List<String>> data = new ArrayList<>();
if (!CollectionUtils.isEmpty(dataList)) {
dataList.forEach(map -> {
List<String> list = new ArrayList<>();
// for (Entry<String, Object> entry : map.entrySet()) {
// Object value = entry.getValue();
// list.add(value == null ? null : value.toString());
// }
for (String title:headList) {
Object value = map.get(title);
// Object value = entry.getValue();
list.add(value == null ? null : value.toString());
}
data.add(list);
});
}
writer.write0(data, sheet, table);
writer.finish();
servletOutputStream.flush();
} catch (IOException e) {
throw new IOException(e.toString());
} finally {
if (servletOutputStream != null) {
servletOutputStream.close();
}
}
}
}
- 编写controller测试
package com.it2.springbootweb2.controller;
import com.it2.springbootweb2.util.ExcelExportUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
/**
* 导出excel
*/
@Controller
public class ExportExcelController {
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<String> headList = Arrays.asList("姓名", "地址");
List<LinkedHashMap<String, Object>> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("姓名", "张三" + i);
map.put("地址", "北京" + i);
dataList.add(map);
}
ExcelExportUtils.exportExcel(headList, dataList, "学生名单1", "某校学生名单", response);
}
}
- 启动项目测试,访问http://localhost:8081/exportExcel,即可导出文件。
导入excel
- 添加依赖
<!-- excel导入导出插件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
- 编写excel工具类
package com.it2.springbootweb2.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Excel读取,支持xls和xlsx
*
* @author leng
*/
public class ExcelReadUtil {
/**
* excel读取器
*/
private static final ExcelReadUtil excelReader = new ExcelReadUtil();
/**
* 总行数
*/
private int totalRows = 0;
/**
* 总列数
*/
private int totalCells = 0;
/**
* 错误信息
*/
private String errorInfo;
/**
* 构造方法
*/
public ExcelReadUtil() {
}
public int getTotalRows() {
return totalRows;
}
public int getTotalCells() {
return totalCells;
}
public String getErrorInfo() {
return errorInfo;
}
public boolean validateExcel(String filePath) {
/** 检查文件名是否为空或者是否是Excel格式的文件 */
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorInfo = "not excel," + filePath;
return false;
}
/** 检查文件是否存在 */
File file = new File(filePath);
if (file == null || !file.exists()) {
errorInfo = "not exist," + filePath;
return false;
}
return true;
}
private List<List<String>> read(String filePath) {
List<List<String>> dataLst = new ArrayList<List<String>>();
InputStream is = null;
try {
/** 验证文件是否合法 */
if (!validateExcel(filePath)) {
System.out.println(errorInfo);
return null;
}
/** 判断文件的类型,是2003还是2007 */
boolean isExcel2003 = true;
if (isExcel2007(filePath)) {
isExcel2003 = false;
}
/** 调用本类提供的根据流读取的方法 */
File file = new File(filePath);
is = new FileInputStream(file);
dataLst = read(is, isExcel2003);
is.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
/** 返回最后读取的结果 */
return dataLst;
}
public List<List<String>> read(InputStream inputStream, boolean isExcel2003) {
List<List<String>> dataLst = null;
try {
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
if (isExcel2003) {
wb = new HSSFWorkbook(inputStream);
} else {
wb = new XSSFWorkbook(inputStream);
}
dataLst = read(wb);
} catch (IOException e) {
e.printStackTrace();
}
return dataLst;
}
private List<List<String>> read(Workbook wb) {
List<List<String>> dataLst = new ArrayList<List<String>>();
/** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
this.totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列数 */
if (this.totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
/** 循环Excel的行 */
for (int r = 0; r < this.totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
List<String> rowLst = new ArrayList<String>();
/** 循环Excel的列 */
for (int c = 0; c < this.getTotalCells(); c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
rowLst.add(cellValue);
}
/** 保存第r行的第c列 */
dataLst.add(rowLst);
}
return dataLst;
}
public static void main(String[] args) throws Exception {
List<List<String>> list = ExcelReadUtil.readExcel("D:\\readExcel.xls");
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.print("第" + (i) + "行");
List<String> cellList = list.get(i);
for (int j = 0; j < cellList.size(); j++) {
// System.out.print(" 第" + (j + 1) + "列值:");
System.out.print(" " + cellList.get(j));
}
System.out.println();
}
}
}
/**
* 读取excel,首列如果内容前缀为##,则不会被读取
*
* @param filePath
* @return
*/
public static List<List<String>> readExcel(String filePath) {
synchronized (excelReader) {
List<List<String>> list = excelReader.read(filePath);
if (null != list && list.size() > 0) {
List<Integer> deleteList = new ArrayList<>();// 需要删除的行
for (int i = 0; i < list.size(); i++) {
List<String> row = list.get(i);
if (null != row && row.size() > 0) {
String firstRow = row.get(0);
if (firstRow.startsWith("##")) {
deleteList.add(i);
}
}
}
for (int i = deleteList.size() - 1; i >= 0; i--) {
int index = deleteList.get(i);
list.remove(index);
}
}
return list;
}
}
/**
* 读取excel,首列如果内容前缀为##,则不会被读取
*
* @param filePath
* @return
*/
public static List<String[]> readExcel2(String filePath) {
List<List<String>> list = readExcel(filePath);
List<String[]> resultList = new ArrayList<>(list.size());
for (List<String> listTemp : list) {
String[] strArr = new String[listTemp.size()];
for (int i = 0; i < listTemp.size(); i++) {
strArr[i] = listTemp.get(i);
}
resultList.add(strArr);
}
return resultList;
}
/**
* 读取excel,首列如果内容前缀为##,则不会被读取
*
* @param filePath
* @return
*/
public static List<Map<String, String>> readExcel3(String filePath) {
List<List<String>> list = readExcel(filePath);
if (null == list || list.size() <= 1) {
return null;
}
List<Map<String, String>> listMap = new ArrayList<>(list.size() - 1);
List<String> title = list.get(0);
for (int i = 1; i < list.size(); i++) {
Map<String, String> map = new HashMap<>();
List<String> childList = list.get(i);
for (int j = 0; j < title.size(); j++) {
map.put(title.get(j), childList.get(j));
}
listMap.add(map);
}
return listMap;
}
/**
* 是否是xls文件,95~2003的excel文件
*
* @param filePath
* @return
*/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* 是否能是xlsx文件,excel2017以上的格式
*
* @param filePath
* @return
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
- 编写controller测试
package com.it2.springbootweb2.controller;
import com.it2.springbootweb2.util.ExcelReadUtil;
import com.it2.springbootweb2.util.UnicodeUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.List;
/**
* 导入excel
*/
@Controller
public class ImportExcelController {
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
String fileName = request.getParameter("fileName");
System.out.println("从file获取的文件名:"+ UnicodeUtils.webUnicodeToString(file.getOriginalFilename()));
System.out.println("前端提交的文件名:"+ URLDecoder.decode(fileName,"UTF-8"));
List<List<String>> list = new ExcelReadUtil().read(file.getInputStream(), false);
list.forEach(li -> {
System.out.println(li);
});
return "ok";
}
}
- webunicode转中文
package com.it2.springbootweb2.util;
/**
* Unicode
*
* @author leng
*/
public class UnicodeUtils {
/*
* web类型的unicode转string
*/
public static String webUnicodeToString(String input) {
String str = "";
String[] array = input.split(";");
for (String st : array) {
int idx = st.lastIndexOf("&#");
if (idx > -1) {
String str1 = st.substring(0, idx);
String str2 = st.substring(idx + 2);
if (st.length() > 2) {
str = str + str1;
str = str + (char) Integer.parseInt(str2);
}
} else {
str = str + st;
}
}
return str;
}
}
- 编写一个index.html页面用于上传excel文件,文件位置位于resources/static目录下
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<head>
<title>example</title>
</head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<body>
<hr>
<h1>import excel</h1>
<form action="/uploadFile"
enctype="multipart/form-data" method="post">
file <input type="file" name="file" id="file" onchange='$("#fileName").val(encodeURI($("#file").val()));'>
<input type="hidden" value="" id="fileName" name="fileName" >
<br><br>
<input type="submit" value="submit">
</form>
<hr>
</body>
</html>
- 启动服务器测试,访问http://localhost:8081/,选择excel文件上传(请使用xlsx后缀的excel文件),查看控制台输出
上传文件获取文件名(中文文件名问题)
上面的代码通过前端的方式获取文件名,并通过fileName字段发送到服务端,对于中文文件名的文件,只要简单的编码和转码即可。
也可以直接获取 file.getOriginalFilename()获取文件名,只不过如果是中文文件名,返回的unicode码,需要转换即可,需要在服务端进行一次编码转换即可。
xls和xlsx文件的区别
区别:1、xls是excel 2007之前版本的使用的默认格式;xlsx是excel 2007之后的版本使用的默认格式,包括2007的版本。2、XLSX格式的占用空间比XLS的小。
导入xls文件时,请注意修改代码,isExcel2003应当设置为true。
当然,推荐导入导出都使用xlsx文件。