Java (新)将Excel数据读取到ListMap

Maven依赖: pom.xml

<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>

Controller访问类:

    @Controller
@RequestMapping("/excel")
public class ImportExcelController { @RequestMapping(value = "/readto/listmap", method = { RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String readExcelToListMap(MultipartFile upfile,HttpServletRequest request, HttpServletResponse response) {
ReturnResult result = ExcelUtil.readExcelDataToReturnResult(upfile);
if (200 == result.getStatus()) {
List<Map<String, Object>> listMap = (List<Map<String, Object>>) result.getData();
if (listMap.size() > 0) {
for (Map<String, Object> map : listMap) {
System.out.println(map.toString());
}
return ReturnResult.objectToJson(ReturnResult.build(200, "导入成功 ",null));
}else{
return ReturnResult.objectToJson(ReturnResult.build(300, "文件内容读取为空!"));
}
}else{
return ReturnResult.objectToJson(result);
}
}
}

Excel工具类:

    import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
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;
import org.springframework.web.multipart.MultipartFile;
import com.test.common.pojo.ReturnResult; public class ExcelUtil { /**
* 将Excel数据读取到ListMap
* @param file
* 仅支持 csv,xls,XLS,XLs,Xls,xlsx
*/
public static ReturnResult readExcelDataToReturnResult(MultipartFile file) {
if (null != file) {
String fileName = file.getOriginalFilename(); // 获取文件名
if (StringUtils.isNotBlank(fileName)) {
if (fileName.toLowerCase().matches("^.*(csv)$")) {
try {
List<Map<String,Object>> listMap = getResource(file.getBytes());
return ReturnResult.build(200, "成功",listMap);
} catch (Exception e) {
e.printStackTrace();
return ReturnResult.build(500, "系统繁忙,请稍后再试!");
}
}else{
if (fileName.toLowerCase().matches("^.*(xls|XLS|XLs|Xls|xlsx)$")) {
String edition_2003 = "^.+\\.(?i)(xls)$"; // Excel_2003版本
String edition_2007 = "^.+\\.(?i)(xlsx)$"; // Excel_2007版本
try {
// 根据Excel版本创建对象
Workbook wb = null;
if (fileName.matches(edition_2003)) {
wb = new HSSFWorkbook(file.getInputStream());
} else {
if (fileName.matches(edition_2007)) {
wb = new XSSFWorkbook(file.getInputStream());
}
}
// 读取Excel里面的数据
if (null != wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
int totalCells = 0;
if (totalRows > 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
// 循环Excel行数
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
// 循环Excel的列
Map<String, Object> map = new HashMap<String, Object>();
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
int cellType = cell.getCellType();
if (cellType == 0) {
DataFormatter dataFormatter = new DataFormatter();
dataFormatter.addFormat("###########", null);
String str = dataFormatter.formatCellValue(cell);
if (StringUtils.isNotBlank(str)) {
map.put(c+"",str);
}
}else{
String str = String.valueOf(cell);
if (StringUtils.isNotBlank(str)) {
map.put(c+"",str);
}
}
}
}
// 添加到list
if (map.size() > 0) {
listMap.add(map);
}
}
return ReturnResult.build(200, "成功",listMap);
}else{
return ReturnResult.build(300, "读取文件内容为空!");
}
} catch (Exception e) {
e.printStackTrace();
return ReturnResult.build(500, "系统繁忙,请稍后再试!");
}
}else{
return ReturnResult.build(300, "文件格式错误,仅支持 xls,XLS,XLs,Xls,xlsx后缀的文件!");
}
}
}else{
return ReturnResult.build(300, "文件名不能为空!");
}
}else{
return ReturnResult.build(300, "文件不能为空!");
}
} /** 获取csv文件内容 **/
private static List<Map<String,Object>> getResource(byte[] bate) throws IOException {
List<Map<String,Object>> allString = new ArrayList<>();
// 获取文件内容
List<String> list = getSource(bate);
if (list.size() > 1) {
Map<String,Object> callLogInfo = new HashMap<>(); // 循环内容
for(int i = 1; i<list.size();i++){
List<String> content = Arrays.asList(list.get(i).split(","));
if(content!=null && content.size()>0){
callLogInfo = new HashMap<>();
for (int j = 0; j < content.size(); j++) {
callLogInfo.put(j+"",content.get(j));
}
allString.add(callLogInfo);
}
}
}
return allString;
} /** 读文件数据 **/
private static List<String> getSource(byte[] bate) throws IOException {
BufferedReader br = null;
ByteArrayInputStream fis=null;
InputStreamReader isr = null;
try {
fis = new ByteArrayInputStream(bate);
isr = new InputStreamReader(fis,"GB2312");
br = new BufferedReader(isr);
} catch (Exception e) {
e.printStackTrace();
}
String line;
String everyLine ;
List<String> allString = new ArrayList<>();
try {
//读取到的内容给line变量
while ((line = br.readLine()) != null){
everyLine = line;
allString.add(everyLine.trim());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis != null){
fis.close();
}
if(isr != null){
isr.close();
}
}
return allString;
} }

最新文章

  1. IE8 下 iframe 滚动条的问题
  2. leetcode 119 Pascal&#39;s Triangle II ----- java
  3. 64位Win8系统下安装Oracle12c
  4. gdb调试运行时的程序小技巧
  5. HDOJ 2036
  6. Scala 编程(四)内建控制结构
  7. 谈谈Ext JS的组件——布局的用法续二
  8. Android面试之高级篇
  9. stream,file,filestream,memorystream简单的整理
  10. php代码进行跨域请求处理
  11. Docker公共&amp;本地镜像仓库(七)--技术流ken
  12. 去除编辑器的HTML标签
  13. 利用Python生成GIF动图
  14. 删除oracle 表中重复数据sql语句、保留rowid最小的一条记录
  15. 微信小程序 - 上传图片组件
  16. SIM800C 透传模式
  17. UVA 624(01背包记录路径)
  18. codeforces 1000F One Occurrence(线段树、想法)
  19. Pygame:编写一个小游戏 标签: pythonpygame游戏 2017-06-20 15:06 103人阅读 评论(0)
  20. linux漏洞分析入门笔记-栈溢出

热门文章

  1. shell, 进程, 变量, 命令, 作业控制
  2. Nginx负载均衡4种方案
  3. python实现web应用程序(1)虚拟环境与Django
  4. 实验室服务器运维踩坑o.0
  5. Mac聚焦搜索无法搜索应用问题处理
  6. 看K线学炒股(8.9)
  7. shell特殊符号
  8. react 脚手架搭建项目 报错C:\Program Files\nodejs\node_cache\_logs\2022-12-28T14_38_28_286Z-debug-0.log
  9. WC2023 游记
  10. v4l2编程