java解析excel表格数据

package com.hans.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hans.pojo.Orderinfo;

@Controller
@RequestMapping("/xcel")
public class Excel_xls {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
@RequestMapping("/findexcel")
public String excel(HttpServletRequest request) throws Exception
{

/*File excelFile = new File("C:\fakepath\123.xlsx"); //替换你文档地址
XSSFWorkbook wb = null;
try {
wb = new XSSFWorkbook(new FileInputStream(excelFile));
} catch (IOException e) {
e.printStackTrace();
}
int numberOfSheets = wb.getNumberOfSheets();
String str = "";*/
MultipartHttpServletRequest mult=(MultipartHttpServletRequest) request;

MultipartFile file=mult.getFile("pic");
if(file.isEmpty()){
System.out.println("文件为空");
}else{
System.out.println("文件不为空");
}
InputStream in = null;
in = file.getInputStream();
List list= getBankListByExcelTitle(in, file.getOriginalFilename(), 14);
for( int i=0;i<list.size();i++){
//System.out.println(list.get(i));
List one=(List) list.get(i);
/*for(int j=0;j<one.size();j++){
System.out.println(one.get(j));
}*/
Orderinfo orderinfo=new Orderinfo();

String first=(String) one.get(0);

orderinfo.setContractName(first);
}
return null;
}

/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName
* @return
* @throws IOException
*/
public static List<List<Object>> getBankListByExcelTitle(InputStream in,String fileName,Integer lastCellNum) throws Exception{
List<List<Object>> list = null;

//创建Excel工作薄 技术部
Workbook work = getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;

list = new LinkedList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}

//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getPhysicalNumberOfRows(); j++) {
row = sheet.getRow(j);
/*if(row==null||row.getFirstCellNum()==j){continue;}*/

//遍历所有的列
List<Object> link = new LinkedList<Object>();

int xx1=row.getLastCellNum();
int xx2=0;
if(lastCellNum == null) {
lastCellNum = Integer.valueOf(row.getLastCellNum());
}
for (int y = row.getFirstCellNum(); y < row.getLastCellNum() && y < lastCellNum; y++) {
cell = row.getCell(y);
Object val=getCellValue(cell);
if(cell==null || val==null || val.equals("")|| val.equals(" ")){
xx2++;
}
link.add(val);
}
if(xx1==xx2 || xx2 == lastCellNum){
continue;
}
list.add(link);
}
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}

/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字

if(cell != null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString().trim();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
String str=cell.getNumericCellValue()+"";
String[] strs=str.split("\\.");
double str1=Double.parseDouble(strs[1]);
if(str1>0){
value = df2.format(cell.getNumericCellValue()).trim();
}else{
value = df.format(cell.getNumericCellValue()).trim();
}
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue()).trim();
}else{
value = df2.format(cell.getNumericCellValue()).trim();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
}

return value;
}
}

html页面

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript"> function show() { var c=document.getElementById("pic").value;

}
</script>

<body> <form action="/SSM/xcel/findexcel" method="post" enctype="multipart/form-data"> <input type="file" name="pic" id="pic" /> <input type="submit" onclick="show()" value="提交"> </form> </body> </html>

springMVC记得配置文件上传

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )