java+jsp导入excel
2016-05-16 11:45
507 查看
jsp
<button onclick="shouye();" style="float: right;">返回首页</button>
<form id="excelForm" enctype="multipart/form-data" method="post" style="">
<table id="mainForm" >
<tr>
<td> 上传文件:</td>
<td><input type="file" name="file" id="files" onchange="importExcel()" /></td>
</tr>
<tr>
<td colspan="2" style="padding-top:3em; text-align: center; padding-right: 140px;">
<input type="submit" value="导入excel" onclick="isnull()" /></td>
<td> </td>
</table>
</form>
javascript
<script type="text/javascript">
var filePath;
function importExcel(){
var filename=$("#files").val();
var filePath=filename.substring(11,filename.length);
$('#excelForm').attr('action','${pageContext.request.contextPath}/`````````_importExcel.action?filePath='+filePath);
}
function shouye(){
window.location.href='${pageContext.request.contextPath}/`````````.test2.action';
}
</script>
action
private InputStream inputStream;
private String filePath; //文件路劲(全名称)
private File file;
//文件
//提交过来的file的名字
必须有
private String fileFileName;
//提交过来的file的MIME类型
private String fileContentType;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
/**
* 导入excel
* @return
* @throws IOException
*/
public String test2() throws IOException{
ImportExcel im=new ImportExcel();
String root = ServletActionContext.getServletContext().getRealPath("/importExcel");
InputStream is = new FileInputStream(file);
File files=new File(root);
if (!files.exists()) {
files.mkdir();
}
OutputStream os = new FileOutputStream(new File(root, fileFileName));
byte[] buffer = new byte[500];
int length = 0;
try {
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
im.read(lexiconService,(root+filePath),ClassifyAction.getTypeId());
inputStream =new ByteArrayInputStream("导入成功,且已成功入库".getBytes("utf-8"));
} catch (Exception e) {
try {
inputStream =new ByteArrayInputStream("导入失败".getBytes("utf-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
return "importExcel";
}
ImportExcel (导入类)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javassist.compiler.Lex;
import javax.annotation.Resource;
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;
import org.bigdatacn.sfgk.filter.action.BaseAction;
import org.bigdatacn.sfgk.filter.service.LexiconService;
import org.bigdatacn.sfgk.filter.service.impl.LexiconServiceImpl;
import org.bigdatacn.sfgk.wlzbs.domain.Lexicon;
import org.bigdatacn.sfgk.wlzbs.domain.User;
import org.springframework.stereotype.Controller;
public class ImportExcel{
InputStream stream;
public void read(LexiconService lexiconService,String filePath,int typeId) throws IOException, ParseException {
String fileType = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
InputStream stream = new FileInputStream(filePath);
Workbook wb = null;
if (fileType.equals("xls")) {
wb = new HSSFWorkbook(stream);
}else if (fileType.equals("xlsx")) {
wb = new XSSFWorkbook(stream);
}else {
System.out.println("您输入的excel格式不正确");
}
Sheet sheet1 = wb.getSheetAt(0);
int num=0;
for (Row row : sheet1) {
if (num==0 || num==sheet1.getLastRowNum()) {
num++;
continue;
}
if (null== row.getCell(2) || row.getCell(2).toString()=="" ) {//若主要内容 没写 则不予通过
break;
}
实体类 le=new 实体();
le.setCreateDate(new SimpleDateFormat("yyyy-mm-dd hh:MM:ss").parse(row.getCell(1).toString()));
le.setContains(row.getCell(2).toString());
le.setType(typeId);
try {
System.out.println(lexiconService);
lexiconService.saveInfo(le);
} catch (Exception e) {
System.out.println("保存saveInfo失败");
}
}
}
}
maven的方式,在pom.xml中的配置
<!-- 加入POI核心依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
若是不用maven的方式,则需要导入jar包
<button onclick="shouye();" style="float: right;">返回首页</button>
<form id="excelForm" enctype="multipart/form-data" method="post" style="">
<table id="mainForm" >
<tr>
<td> 上传文件:</td>
<td><input type="file" name="file" id="files" onchange="importExcel()" /></td>
</tr>
<tr>
<td colspan="2" style="padding-top:3em; text-align: center; padding-right: 140px;">
<input type="submit" value="导入excel" onclick="isnull()" /></td>
<td> </td>
</table>
</form>
javascript
<script type="text/javascript">
var filePath;
function importExcel(){
var filename=$("#files").val();
var filePath=filename.substring(11,filename.length);
$('#excelForm').attr('action','${pageContext.request.contextPath}/`````````_importExcel.action?filePath='+filePath);
}
function shouye(){
window.location.href='${pageContext.request.contextPath}/`````````.test2.action';
}
</script>
action
private InputStream inputStream;
private String filePath; //文件路劲(全名称)
private File file;
//文件
//提交过来的file的名字
必须有
private String fileFileName;
//提交过来的file的MIME类型
private String fileContentType;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
/**
* 导入excel
* @return
* @throws IOException
*/
public String test2() throws IOException{
ImportExcel im=new ImportExcel();
String root = ServletActionContext.getServletContext().getRealPath("/importExcel");
InputStream is = new FileInputStream(file);
File files=new File(root);
if (!files.exists()) {
files.mkdir();
}
OutputStream os = new FileOutputStream(new File(root, fileFileName));
byte[] buffer = new byte[500];
int length = 0;
try {
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
im.read(lexiconService,(root+filePath),ClassifyAction.getTypeId());
inputStream =new ByteArrayInputStream("导入成功,且已成功入库".getBytes("utf-8"));
} catch (Exception e) {
try {
inputStream =new ByteArrayInputStream("导入失败".getBytes("utf-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
return "importExcel";
}
ImportExcel (导入类)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javassist.compiler.Lex;
import javax.annotation.Resource;
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;
import org.bigdatacn.sfgk.filter.action.BaseAction;
import org.bigdatacn.sfgk.filter.service.LexiconService;
import org.bigdatacn.sfgk.filter.service.impl.LexiconServiceImpl;
import org.bigdatacn.sfgk.wlzbs.domain.Lexicon;
import org.bigdatacn.sfgk.wlzbs.domain.User;
import org.springframework.stereotype.Controller;
public class ImportExcel{
InputStream stream;
public void read(LexiconService lexiconService,String filePath,int typeId) throws IOException, ParseException {
String fileType = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
InputStream stream = new FileInputStream(filePath);
Workbook wb = null;
if (fileType.equals("xls")) {
wb = new HSSFWorkbook(stream);
}else if (fileType.equals("xlsx")) {
wb = new XSSFWorkbook(stream);
}else {
System.out.println("您输入的excel格式不正确");
}
Sheet sheet1 = wb.getSheetAt(0);
int num=0;
for (Row row : sheet1) {
if (num==0 || num==sheet1.getLastRowNum()) {
num++;
continue;
}
if (null== row.getCell(2) || row.getCell(2).toString()=="" ) {//若主要内容 没写 则不予通过
break;
}
实体类 le=new 实体();
le.setCreateDate(new SimpleDateFormat("yyyy-mm-dd hh:MM:ss").parse(row.getCell(1).toString()));
le.setContains(row.getCell(2).toString());
le.setType(typeId);
try {
System.out.println(lexiconService);
lexiconService.saveInfo(le);
} catch (Exception e) {
System.out.println("保存saveInfo失败");
}
}
}
}
maven的方式,在pom.xml中的配置
<!-- 加入POI核心依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
若是不用maven的方式,则需要导入jar包
相关文章推荐
- maven基础篇(5)-eclipse构建maven-web项目
- Java并发编程—阻塞队列源码分析
- Java 堆内存和栈内存详解
- java中JLabel设置背景图片
- 【Java】Java NIO
- java 面向对象练习题
- spring配置文件---之数据库切换
- Java多线程学习笔记(二)
- 在java中序列化与反序列化详解(转载)
- eclipse导入Android工程项目后出现错误汇总
- JAVA中的聚集和组合的区别和联系
- Java中文字符所占的字节数
- java jdbc数据库连接使用
- Spring 框架的设计理念与设计模式分析
- Android studio 无法修改jdk的location
- Java内存模型
- 浅谈Struts2与Webwork的不同和相同点
- Spring 4 Hello World 例子(带源码)
- Spring MVC与Ajax交互实例
- JavaWeb不错的教程01