Java (新)将Excel数据读取到ListMap
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;
}
}
Java (新)将Excel数据读取到ListMap的更多相关文章
- Java向指定Excel写入读取数据
今天在开发中遇到用户列表导入导出的功能实现,这里了解到使用POI函数库可以完成此任务!特此记录一下 POI Apache POI是Apache软件基金会开放的源码函数库,POI提供API给Java程序 ...
- Java代码实现excel数据导入到Oracle
1.首先需要两个jar包jxl.jar,ojdbc.jar(注意版本,版本不合适会报版本错误)2.代码: Java代码 import java.io.File; import java.io.Fi ...
- Java:将Excel数据导入到数据库(一眼就看会)
所用Jar包 1. sqljdbc4.jar 连接数据库的Jar包(根据数据库的不同进行选择,我用的SqlServer2008) 2.Jxl.jar 访问Excel的Jar包 注意:支持以.xls结尾 ...
- Java怎样处理EXCEL的读取
须要包:poi-3.5.jar.poi-ooxml-3.5.jar 实例: [java] view plaincopy public class ProcessExcel { private Work ...
- python + Excel数据读取(更新)
data.xlsx 数据如下: import xlrd#1.读取Excel数据# table = xlrd.open_workbook("data.xlsx","r&qu ...
- java数据库导入excel数据
导入数据会将表格分为xls和xlsx两种格式,网上有很多案例 1.excel数据表中的数据不全,数据库中又是必填选项:---从sql语句入手:判断有无 来改变语句 //设置可有可无 字段 加一个必有字 ...
- 自己封装的Java excel数据读取方法
package org.webdriver.autotest.data; import jxl.Workbook; import jxl.Sheet; import jxl.Cell; import ...
- 数据驱动ddt+excel数据读取
我们可以将测试数据用excel存储,再用ddt去传入,不过我们需要安装对应的库,因为python是无法操作excel的 1.安装第三方库xlrd 2.创建一个excel表格,将需要测试的数据保存 3. ...
- python新添加excel数据
相关库 import os import xlwt from xlrd import open_workbook from xlutils.copy import copy 1.判断是否存在xls文件 ...
- python应用_读取Excel数据列表输出【一】
python能使用xlrd模块实现对Excel数据的读取,且按照想要的输出形式. 1.准备Excel数据如下: 2.下面主要是对Excel数据读取后以双列表(每一行是一个用例为一个列表,再一个个案例组 ...
随机推荐
- spring boot2 jpa分页查询百万级数据内存泄漏
分页查询百万级数据,查询处理过程中发现内存一直飙升,最终处理程序会挂掉,通过jvisualvm可以发现频繁ygc 和fgc ,另外通过 jmap -histo:live ${pid} 命令可以看到jp ...
- 百题计划-6 codeforces 651 div2 E. Binary Subsequence Rotation 01序列集合划分,2个队列处理
https://codeforces.com/contest/1370/problem/E 队列元素以末尾字符为结尾的序列就好了,这里队列里的元素不重要,队列size重要 #include<bi ...
- Windows Codename"Longhorn" Build 4074体验
Windows Codename"Longhorn" Build 4074体验 Wimndows Coodename "Longhorn"就是WindowsVi ...
- wpf treeview 选中节点加载数据并绑定
<TreeView Grid.Row="0" Grid.Column="0" x:Name="FolderView" Canvas.T ...
- 【godis】skiplist
skiplist 前言:在看代码时看到 ZSKIPLIST_MAXLEVEL = 32,当时并不了解 ZSKIPLIST_P 的作用,想着用 2 分法不应该层数是 64 吗?书上和他人的代码都是基于 ...
- 1.Easy Touch 3.1
Easy Touch 3.1 Hedgehog Team(导入 Easy Touch 插件时自动在菜单栏) Extensions: 拓展 Adding a new joytick: 虚拟摇杆 Addi ...
- Oracle11gR2安装
https://blog.csdn.net/newbie_907486852/article/details/80716275
- SQLSERVER 根据一个库的视图在另一个库中生成一张表
select * into VPsiOuntStockBill from [KshDbPro].dbo.VPsiOuntStockBill
- STM32-USART打印字符、字符串函数自己犯的错误反思
void UART_Send_Byte(USART_TypeDef *USARTx, uint8_t cha) { USART_SendData(USARTx, cha); while(USART_G ...
- QSlider CSS样式
QSlider::groove:horizontal{ border:0px; height:15px; background:#deffe5; } QSlider::sub-page:horizon ...