java读取excel文件(.xls,xlsx,csv)
前提,maven工程通过poi读写excel文件,需要在pom.xml中配置依赖关系:
在<dependencies>中添加如下代码
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
1,页面标签及属性
input[type="button"]{background-color: #71BCF3;color: white;}
<form name="form" id="form" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="upload"style="display: none;"
onchange="document.form.path.value=this.value" multiple="multiple" accept=".xls,.xlsx,.csv" />
<input name="path" id="path" readonly>
<input type="button" value="医路通数据文件上传" onclick="document.form.upload.click()">
</form>
<input type="button" value="确定" onclick="readFile()">
function readFile(){
var f = document.getElementById("form");
f.action = "<%=request.getContextPath()%>/mcp/MedicalDate/readExls.action?";
f.submit();
}
特别注意 : (一),提交文件标签的数据,一定要用form的action提交,否则有数据缺失 (二),form标签中,必须要有 enctype="multipart/form-data"
2,后台用@RequestParam(value = "upload") MultipartFile upload接文件数据
@RequestMapping("/readExls")
public ModelAndView readExls(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "upload") MultipartFile upload) throws IOException
{
String oldFile = upload.getOriginalFilename();
String suffix = oldFile.substring(oldFile.lastIndexOf("."));
log.info("oldFile:"+oldFile);//文件名
log.info("suffix:"+suffix);//文件后缀
InputStream inStream = upload.getInputStream();//文件流,可直接用
}
3,解析xls后缀文件将数据转换成为List<MedicalWhiteListVO>,以便对数据操作
public List<MedicalWhiteListVO> readXls(InputStream inStream) throws IOException
{ InputStream is = inStream;
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); List<MedicalWhiteListVO> medicalWhiteListVOs = new ArrayList<MedicalWhiteListVO>();
MedicalWhiteListVO medicalvo = null; // Read the Sheet
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0); if (hssfSheet == null) {
//continue;
return medicalWhiteListVOs;
} int lastRowNum = hssfSheet.getLastRowNum(); // Read the Row
for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) {
medicalvo = new MedicalWhiteListVO(); HSSFCell holderMobile = hssfRow.getCell(0);
HSSFCell holderRealName = hssfRow.getCell(1); HSSFCell holderBirthday = hssfRow.getCell(2);
HSSFCell policyApplyDate = hssfRow.getCell(3); medicalvo.setHolderMobile(getValue(holderMobile));
medicalvo.setHolderRealName(getValue(holderRealName)); try
{
medicalvo.setHolderBirthday(getDate(getValue(holderBirthday)));
medicalvo.setPolicyApplyDate(getDate(getValue(policyApplyDate)));
} catch (Exception e)
{
e.printStackTrace();
log.info("**日期格式转换异常*2222***");
} medicalWhiteListVOs.add(medicalvo);
}
}
return medicalWhiteListVOs;
}
public static Date getDate(String date) throws Exception{ Pattern pattern = Pattern.compile("^[0-9]*$");
Matcher matcher = pattern.matcher(date);
//判断是否可以转换成日期
if(StringUtils.isNullOrEmpty(date) || !matcher.matches()){
Date defaultDate = DateUtils.parse("1900-01-01");
System.out.println(DateUtils.format(defaultDate));
return defaultDate;
} Double str = Double.valueOf(date); int numday = (int) Math.round(str); Calendar d = Calendar.getInstance();
d.set(1900, 0, 1);
d.add(Calendar.DAY_OF_MONTH,numday); int year = d.get(Calendar.YEAR);
int month = d.get(Calendar.MONTH) + 1;
int day = d.get(Calendar.DAY_OF_MONTH)-2; String dateStr = year+"-"+month+"-"+day; Date newDate = DateUtils.parse(dateStr); System.out.println(DateUtils.format(newDate)); return newDate;
}
private static String getValue(HSSFCell hssfCell) { if(hssfCell==null){
return "";
} if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int)hssfCell.getNumericCellValue());
}else {
return String.valueOf(hssfCell.getStringCellValue()==null?"":hssfCell.getStringCellValue());
}
}
4,解析xlsx后缀文件将数据转换成功List<MedicalWhiteListVO>,以便对数据操作
public static List<MedicalWhiteListVO> readXlsx(InputStream inStream) throws IOException
{
//InputStream is = new FileInputStream(path); InputStream is = inStream; XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is); List<MedicalWhiteListVO> medicalWhiteListVOs = new ArrayList<MedicalWhiteListVO>();
MedicalWhiteListVO medicalvo = null; // Read the Sheet
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); if (xssfSheet == null) {
return medicalWhiteListVOs;
} // Read the Row
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) { XSSFRow xssfRow = xssfSheet.getRow(rowNum); if (xssfRow != null) {
medicalvo = new MedicalWhiteListVO(); XSSFCell holderMobile = xssfRow.getCell(0);
XSSFCell holderRealName = xssfRow.getCell(1);
XSSFCell holderBirthday = xssfRow.getCell(2);
XSSFCell policyApplyDate = xssfRow.getCell(3); medicalvo.setHolderMobile(getValue(holderMobile));
medicalvo.setHolderRealName(getValue(holderRealName)); try
{
medicalvo.setHolderBirthday(getDate(getValue(holderBirthday)));
medicalvo.setPolicyApplyDate(getDate(getValue(policyApplyDate)));
} catch (Exception e)
{
e.printStackTrace();
log.info("**日期格式转换异常*2***");
}
medicalWhiteListVOs.add(medicalvo);
}
} return medicalWhiteListVOs;
}
private static String getValue(XSSFCell xssfRow) {
if(xssfRow==null){
return "";
}
if (xssfRow.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int)xssfRow.getNumericCellValue());
}else {
return String.valueOf(xssfRow.getStringCellValue()==null?"":xssfRow.getStringCellValue());
}
}
public static Date getDate(String date) throws Exception{ Pattern pattern = Pattern.compile("^[0-9]*$");
Matcher matcher = pattern.matcher(date);
//判断是否可以转换成日期
if(StringUtils.isNullOrEmpty(date) || !matcher.matches()){
Date defaultDate = DateUtils.parse("1900-01-01");
System.out.println(DateUtils.format(defaultDate));
return defaultDate;
} Double str = Double.valueOf(date); int numday = (int) Math.round(str); Calendar d = Calendar.getInstance();
d.set(1900, 0, 1);
d.add(Calendar.DAY_OF_MONTH,numday); int year = d.get(Calendar.YEAR);
int month = d.get(Calendar.MONTH) + 1;
int day = d.get(Calendar.DAY_OF_MONTH)-2; String dateStr = year+"-"+month+"-"+day; Date newDate = DateUtils.parse(dateStr); System.out.println(DateUtils.format(newDate)); return newDate;
}
4,解析csv后缀文件将数据转换成功List<MedicalWhiteListVO>,以便对数据操作
public static List<MedicalWhiteListVO> readCsv(InputStream inStream) throws IOException
{
List<MedicalWhiteListVO> medicalWhiteListVOs = new ArrayList<MedicalWhiteListVO>();
MedicalWhiteListVO medicalvo = null; try {
//BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(path),"GBK")); BufferedReader reader=new BufferedReader(new InputStreamReader(inStream,"GBK"));
//换成你的文件名 reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉
String line = null;
int num = 0;
while((line=reader.readLine())!=null){
num ++;
String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分 medicalvo = new MedicalWhiteListVO(); medicalvo.setHolderMobile(getValue(item,0));
medicalvo.setHolderRealName(getValue(item,1));
medicalvo.setHolderBirthday(getCsvDate(getValue(item,2)));
medicalvo.setPolicyApplyDate(getCsvDate(getValue(item,3)));
medicalWhiteListVOs.add(medicalvo); } Log.info("**一共行数**:"+num); } catch (Exception e) {
e.printStackTrace();
} return medicalWhiteListVOs;
}
public static String getValue(String[] item,int index){ if(item.length > index){
String value = item[index];
return value;
}
return "";
}
public static Date getCsvDate(String item) throws Exception{ if(item.indexOf("/") > 0){
item = item.replaceAll("/", "-");
}else if(item.indexOf("年") > 0){
item = item.replaceAll("年", "-").replaceAll("月", "-").replaceAll("日","");
} Date birth = DateUtils.parse(item);
Date defaultDate = DateUtils.parse("1900-01-01"); if(birth.getTime() <= defaultDate.getTime()){
return defaultDate;
}
return birth;
}
注意java通过poi编写excel文件,需要工程共引入的jar有:
dom4j-1.6.1.jar
poi-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
xmlbeans-2.3.0.jar
xml-resolver-1.2.jar
xmlschema-core-2.0.2.jar
xstream-1.3.1.jar
this is all over,i hope it helpful for you ,3q~
java读取excel文件(.xls,xlsx,csv)的更多相关文章
- phpexcel读取excel的xls xlsx csv格式
我之前写过一篇PHP读取csv文件的内容 上代码index.php <?php /** * * @author XC * */ class Excel { public $currentShee ...
- 关于解决java读取excel文件遇空行抛空指针的问题 !
关于解决java读取excel文件遇空行抛空指针的问题 ! package exceRead; import java.io.File; import java.io.FileInputStream; ...
- Java读取Excel文件的几种方法
Java读取 Excel 文件的常用开源免费方法有以下几种: 1. JDBC-ODBC Excel Driver 2. jxl.jar 3. jcom.jar 4. poi.jar 简单介绍: 百度文 ...
- java读取excel文件的代码
如下内容段是关于java读取excel文件的内容,应该能对各朋友有所用途. package com.zsmj.utilit; import java.io.FileInputStream;import ...
- java 读取Excel文件并数据持久化方法Demo
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util ...
- java读取excel文件数据导入mysql数据库
这是我来公司的第二周的一个小学习任务,下面是实现过程: 1.建立maven工程(方便管理jar包) 在pom.xml导入 jxl,mysql-connector 依赖 可以在maven仓库搜索 2.建 ...
- JAVA 读取excel文件成List<Entity>
package com.fsinfo.common.utils; import com.fsinfo.modules.enterprise.entity.EnterpriseRecordEntity; ...
- java 读取excel文件(只读取xls文件)
package com.sun.test; import java.io.BufferedInputStream;import java.io.File;import java.io.FileInpu ...
- java读取txt/pdf/xls/xlsx/doc/docx/ppt/pptx
环境准备txt利用common-iopdf利用pdfbox剩下的用POI关于POI,读取xls没啥特别的,主要是读取doc和ppt,需要下载poi源代码,然后将poi-src-3.7-20101029 ...
随机推荐
- 迭代器、生成器 day13
一 迭代器 迭代器的由来pythone2.2引进的,是一种序列(也是一种数据类型),也是为类对象提供一个序列的入口. for 循环str list tuple dict set 文件句柄可迭代: s ...
- 10.16JS日记
1.parseint() 2.parsefloat() 这两个单词运行的时候遇到第一个非数字就结束了 3.var a="hello word" a这个变量为字符串,每一个字母为字 ...
- Apache Commons configuration使用入门
使用Commons Configuration可以很好的管理我们的配置文件的读写, 官网:http://commons.apache.org/configuration 需要用到commons-la ...
- 8M - 三角形
用N个三角形最多可以把平面分成几个区域? Input 输入数据的第一行是一个正整数T(1<=T<=10000),表示测试数据的数量.然后是T组测试数据,每组测试数据只包含一个正整数N(1 ...
- 让键盘输入不影响界面的动态效果(C++)
输入语句,当代码运行到它的时候就要等待输入,才能执行下一行代码,如果不输入的话,就相当于在这里暂停了(程序设计老师讲过通过这样的方式以达到暂停(pause)的效果),但如果我们想要如果没输入仍然可以运 ...
- tensorflow.reshap(tensor,shape,name)的使用说明
tensorflow as tf tf.reshape(tensor, shape, name=None) reshape作用是将tensor变换为指定shape的形式. 其中shape为一个列表形式 ...
- mtcp的快速编译(连接)
mtcp的快速编译 http://mos.kaist.edu/guide/config/03_build_mtcp.html 介绍DPDK中使用mtcp的文档 https://dpdksummit.c ...
- BZOJ1051或洛谷2341 [HAOI2006]受欢迎的牛
BZOJ原题链接 洛谷原题链接 显然在一个强连通分量里的奶牛都可以相互喜欢,所以可以用\(tarjan\)求强连通并缩点. 要求明星奶牛必须被所有人喜欢,显然缩点后的图必须满足只有一个点没有出度,因为 ...
- hdu2870 Largest Submatrix 单调栈
描述 就不需要描述了... 题目传送门 题解 被lyd的书的标签给骗了(居然写了单调队列优化dp??) 看了半天没看出来哪里是单调队列dp,表示强烈谴责QAQ w x y z 可以各自 变成a , ...
- C++变量存储类别和内存四区
变量存储类别 变量声明/定义的一般形式: 存储类别 数据类型 变量名 存储类别指的是数据在内存中存储的方法.存储方法分为静态存储和动态存储两大类.标准C语言为变量.常量和函数定义了4种存储类型:ext ...