基于java的execl导入数据库和取数据至页面

前言

在踩了许多坑之后,急需总结一下来提高自己,当然探索未知的过程也是自我能力的提升

POI

akarta POI 是apache的子项目,它提供了一组操纵Windows文档的Java API,一般我们使用HSSF接口来操作execl对象,从而实现用纯Java代码来读取、写入、修改Excel文件

我们可以到其官网下载最新poi文档

进入正题

首先我们定义一个需求,上传本地一个execl表(里面含有数据),提交给服务器,然后跳转到另一个界面(显示execl表中内容)

环境准备

MyEclipse。ssh整合包,mysql,poi的相关包(去官网下载,导入poi-3.7-20101029.jar,poi-examples-3.7-20101029.jar,poi-ooxml-3.7-20101029.jar,poi-ooxml-schemas-3.7-20101029.jar,poi-scratchpad-3.7-20101029.jar)

  1. 首先是建一个pojo类,主要与execl表中对应的字段相对应
    为了方便,这里只有id,name,password字段

    1
    2
    3
    4
    5
    6
    7
    8
    package com.zwl.pojo;
    public class User {
    private int id;
    private String name;
    private String password;
    省略set..get方法

    2.execl表中写数据

id name password
1 java lol
2 c

3.写读取execl表格的工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.zwl.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import com.zwl.pojo.User;
public class ReadExcel {
//将execl表中的数据读取出,并与pojo类对应,最后放在集合中
public List<User> readXls(String path) throws IOException {
//execl表的全路径,并保存在输入流
InputStream is = new FileInputStream(path);
//HSSFWorkbook excell 文档对象介绍
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
User user=null;
List<User> list=new ArrayList<User>();
// 循环工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
// HSSFSheet excell的表单
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
//HSSFRow excell的行
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
User u = new User();
//HSSFCell excell的格子单元
//这里取出每一行的数据,依次分别添加到pojo对象中,最后放在集合中
HSSFCell no = hssfRow.getCell(0);
HSSFCell name = hssfRow.getCell(1);
HSSFCell age = hssfRow.getCell(2);
int i=(int)Double.parseDouble(getValue(no));
u.setId(i);
u.setName(getValue(name));
u.setPassword(getValue(age));
list.add(u);
}
}}
return list;
}
@SuppressWarnings("static-access")
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
// 返回数值类型的值
return String.valueOf(hssfCell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(hssfCell.getStringCellValue());
}
} }

4.上传execl页面,这里只有主体部分

1
2
3
4
5
//上传至后台的uploadaction,同时规定只能上传execl文件,并且这里的myFile要与后台action中属性对应
<form action="upload.action" enctype="multipart/form-data" method="post">
<input id="share_box" type="file" name="myFile" accept="excel/*"><hr/>
<input id="submit" type="submit" name="" value="分享">
</form>

5.action编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class upload extends ActionSupport {
private File myFile; //上传的图片文件
private String myFileContentType; //文件类型
private String myFileFileName; //文件名
省略set与get方法
@Override
public String execute() throws Exception {
//创建一个输入流
InputStream is = new FileInputStream(myFile);
//设置文件保存目录
String photoPath =
ServletActionContext.getServletContext().getRealPath("");
//建立该文件
File filePhotoPath = new File(photoPath);
//该用户第一次上传则创建
/*if(!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir();
}*/
//解决中文文件名问题,将中文文件转化为uuid码
String extension = FilenameUtils.getExtension(this.getMyFileFileName());
//上传到服务器的execl表的全路径
String s=photoPath+'\\'+filename;
System.out.println(s);
//设置目标文件
File tofile = new File(photoPath,filename);
//使用输出流来包装目标文件
OutputStream os = new FileOutputStream(tofile);
//通过字节输入
byte[] buffer = new byte[1024];
int length = 0;
while((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
//关闭输入流
is.close();
//关闭输出流
os.close();
//引用读取execl表类
ReadExcel rs=new ReadExcel();
//取出execl表中的内容
List<User> list=rs.readXls(s);
//将execl表中取出的数据放在session中,以便在下个界面显示数据
Map session = ServletActionContext.getContext().getSession();
session.put("stu", list);
return super.execute();
}}

6.structs配置文件编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//spring中注入bean
<bean id="upload" class="com.zwl.action.upload">
</bean>
//strucs.xml文件,其中涉及文件上传,必须有拦截栈的设置,ok.jsp为显示execl表格信息
<action name="upload" class="upload">
<result name="success">/ok.jsp</result>
<result name="input">/ok.jsp</result>
<!-- 配置fileUpload拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 配置允许上传文件类型 这里是execl文件格式允许上传-->
<param name="allowedTypes">application/excel,application/vnd.ms-excel</param>
<!-- 配置允许上传文件大小最大值 -->
<param name="maximumSize">5120000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>

7.取出信息在页面显示
通过标签循环取出session中的数据

1
2
3
4
5
<s:iterator value="#session.stu" id="cri">
id:<s:property value="#cri.id" escape="false"/><br/>
name:<s:property value="#cri.name" escape="false"/><br/>
password:<s:property value="#cri.password" escape="false"/><br/>
</s:iterator>

至此我们可以本地上传execl,然后取出表中内容在另一个页面显示信息

导入数据库

同样关键在于通过execl路径,通过工具包取出表中内容(存在集合中),将该集合循环取出放在数据库即可
9.后台插入数据到数据库的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//映射文件
hibernate-mapping package="com.zwl.pojo">
<class name="User" table="user" >
<id name="id" >
<generator class="increment"></generator>
</id>
<property name="name">
</property>
<property name="password">
</property>
</class>
</hibernate-mapping>
//dao层
public interface dengludao {
public void insert(User u);
}
//sercive层
public interface dengluservice {
public void isinsert(User u);
}
//实现类
//dao层实现类
@Override
public void insert(User u) {
this.getHibernateTemplate().save(u);
}
//service层实现类
private dengludao denglu;
@Override
public void isinsert(User u) {
denglu.insert(u);
}
当然最后还得在spring中注入

10.最后在action中修改一下

1
2
3
4
5
6
7
8
9
10
11
12
13
//首先增加组件(spring中注入)
private dengluservice dengluservic;
省略set与get
// 在execute中末尾增加如下代码
for(User u : list){
//循环取出execl表中数据
User ss=new User();
ss.setId(u.getId());
ss.setName(u.getName());
ss.setPassword(u.getPassword());
//循环插入到数据库
dengluservic.isinsert(ss);
}

最后只要我们上传execl文件,就可以先插入数据库,再在另一个页面显示信息了,注意这里有些地方笔者只给出主体代码,其次有些spring中要注入bean,这里省略了

热评文章