您的位置:首页 > 数据库 > MySQL

SSM框架poi导入导出Excel(MySQL)

2018-08-21 16:52 70 查看

Excel导入的MySQL的方法:

浏览器选择excel文件,传至服务端,在服务端解析此excel并将数据导入到数据库中。

源码下载

这里只保存关键代码,详细的源代码可点击上面源码下载前往下载

1,项目结构:

2,导入页面:

jsp:

[code]<table>
<tr>
<td><input type="file" id="upload" name="upload" value="" /></td>
<td><button onclick="uploadFile()">上传</button></td>
<td><button onclick="OutputExce()">导出</button></td>
</tr>
</table>

js:

[code]function uploadFile() {
var file = $("#upload").val();
file = file.substring(file.lastIndexOf('.'), file.length);
if (file == '') {
alert("上传文件不能为空!");
} else if (file != '.xlsx' && file != '.xls') {
alert("请选择正确的excel类型文件!");
} else {
ajaxFileUpload();
}
}
function ajaxFileUpload() {

var formData = new FormData();
var name = $("#upload").val();
formData.append("file", $("#upload")[0].files[0]);
formData.append("name", name);
$.ajax({
url : "excel/InputExcel.do",
type : "POST",
async : false,
data : formData,
processData : false,
contentType : false,
beforeSend : function() {
console.log("正在进行,请稍候");
},
success : function(e) {
if (e == "01") {
alert("导入成功");
} else {
alert("导入失败");
}
}
});
}

function OutputExce() {
window.location.href = "/ExcelDemo/excel/OutputExcel.do";
}

3,服务端解析处理Excel文件:

Controller:

[code]@RequestMapping(value = "/InputExcel.do")
@ResponseBody
public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
String flag = "02";// 上传标志
if (!file.isEmpty()) {
try {
String originalFilename = file.getOriginalFilename();// 原文件名字
log.info("文件名:" + originalFilename);
InputStream is = file.getInputStream();// 获取输入流
flag = excelService.InputExcel(is, originalFilename);
} catch (Exception e) {
flag = "03";// 上传出错
e.printStackTrace();
}
}
return flag;
}

@RequestMapping(value = "/OutputExcel.do", produces = "application/form-data; charset=utf-8")
@ResponseBody
public String OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html,charset=utf-8");

List<EmpT> list = excelService.OutputExcel();

String message = OutputExcel.OutExcel(request, response, list);
if (message.equals("fail")) {
ServletOutputStream out = response.getOutputStream();
message = "导出失败,请重试";
String s = "<!DOCTYPE HTML><html><head><script>alert('" + message + "');</script></head><body></body></html>";
out.print(s);
}
return null;
}

service:

[code]        @Override
public String InputExcel(InputStream is, String originalFilename) {
Map<String,Object> ginsengMap = new HashMap<String,Object>();
List<ArrayList<Object>> list;
if (originalFilename.endsWith(".xls")) {
list = Excel.readExcel2003(is);
} else {
list = Excel.readExcel2007(is);
}
for (int i=0,j=list.size();i<j;i++){
List<Object> row = list.get(i);
ginsengMap.put("name", row.get(0).toString());
ginsengMap.put("sex", row.get(1).toString());
ginsengMap.put("email", row.get(2).toString());
ginsengMap.put("dept_id", row.get(3).toString());
excelMapper.InputExcel(ginsengMap);
}
return "01";
}

@Override
public List<EmpT> OutputExcel() {
return excelMapper.getAll();
}

mapper.xml:

[code]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wei.dao.ExcelMapper">
<resultMap id="BaseResultMap" type="com.wei.entity.EmpT">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="CHAR" property="sex" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="dept_id" jdbcType="INTEGER" property="deptId" />
</resultMap>

<resultMap type="com.wei.entity.EmpT" id="WithDeptResultMap">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="CHAR" property="sex" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="dept_id" jdbcType="INTEGER" property="deptId" />
<!-- 指定联合查询出的部门字段的封装 -->
<association property="deptName" javaType="com.wei.entity.DeptT">
<id column="d_id" property="dId" />
<result column="d_name" property="dName" />
</association>
</resultMap>

<insert id="InputExcel">
insert into wei.emp_t (name,sex,email,dept_id) values
(#{name },#{sex },#{email },#{dept_id },)
</insert>

<sql id="WithDept_Column_List">
e.id, e.name, e.sex, e.email, e.dept_id, d.d_id, d.d_name
</sql>

<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" suffix=")" prefixOverrides="and">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and
#{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem"
open="(" close=")" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>

<select id="getAll" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
FROM emp_t e
left join dept_t d on e.`dept_id`=d.`d_id` order by e.id
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>

</mapper>

4,解析excel的工具类:

excel文件传至服务端:

[code]public static String upload(HttpServletRequest request, HttpServletResponse response) {

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeTh
24271
reshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setHeaderEncoding("UTF-8");
String uploadPath = request.getSession().getServletContext().getRealPath("/") + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return filePath;
}

读取Excel文件:

[code]public static ArrayList<ArrayList<Object>> readExcel2003(InputStream is) {
try {
ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
ArrayList<Object> colList;
HSSFWorkbook wb = new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Object value = null;
for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
colList = new ArrayList<Object>();
if (row == null) {
if (i != sheet.getPhysicalNumberOfRows()) {// 判断是否是最后一行
rowList.add(colList);
}
return rowList;
} else {
rowCount++;
}
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
if (j != row.getLastCellNum()) {
colList.add("");
}
continue;
}
if (null != cell) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
break;
} else {
Double d = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("#.##");
value = df.format(d);
}
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA:
value = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK:
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "非法字符";
break;
default:
value = "未知类型";
break;
}

}
colList.add(value);
}
rowList.add(colList);
}
if (is != null) {
is.close();
}
return rowList;
} catch (Exception e) {
return null;
}
}

public static ArrayList<ArrayList<Object>> readExcel2007(InputStream is) {
try {
ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
ArrayList<Object> colList;
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Object value = null;

for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
colList = new ArrayList<Object>();
if (row == null) {
if (i != sheet.getPhysicalNumberOfRows()) {
rowList.add(colList);
}
return rowList;
} else {
rowCount++;
}
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
if (j != row.getLastCellNum()) {
colList.add("");
}
continue;
}

if (null != cell) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
break;
} else {
Double d = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("#.##");
value = df.format(d);
}
break;

case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;

case HSSFCell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;

case HSSFCell.CELL_TYPE_FORMULA:
value = cell.getCellFormula() + "";
break;

case HSSFCell.CELL_TYPE_BLANK:
value = "";
break;

case HSSFCell.CELL_TYPE_ERROR:
value = "非法字符";
break;

default:
value = "未知类型";
break;
}

}
colList.add(value);
}
rowList.add(colList);
}
if (is != null) {
is.close();
}
return rowList;
} catch (Exception e) {
System.out.println("exception");
return null;
}
}

导出数据到excel并在浏览器下载:

[code]public static String OutExcel(HttpServletRequest request, HttpServletResponse response, List<EmpT> list) throws Exception {

String message = "fail";
String dir = request.getSession().getServletContext().getRealPath("/output");
File fileLocation = new File(dir);
if (!fileLocation.exists()) {
boolean isCreated = fileLocation.mkdir();
if (!isCreated) {
}
}
String webUrl = request.getSession().getServletContext().getRealPath("/output");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd mm-ss");
String createExcelname = df.format(new Date()) + "OutputExcel.xls";
String outputFile = webUrl + File.separator + createExcelname;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0, "emp");
HSSFRow row1 = sheet.createRow(0);
HSSFCell cell0 = row1.createCell(0, HSSFCell.CELL_TYPE_STRING);
HSSFCell cell1 = row1.createCell(1, HSSFCell.CELL_TYPE_STRING);
HSSFCell cell2 = row1.createCell(2, HSSFCell.CELL_TYPE_STRING);
HSSFCell cell3 = row1.createCell(3, HSSFCell.CELL_TYPE_STRING);
HSSFCell cell4 = row1.createCell(4, HSSFCell.CELL_TYPE_STRING);

cell0.setCellValue("id");
cell1.setCellValue("name");
cell2.setCellValue("sex");
cell3.setCellValue("email");
cell4.setCellValue("dept_id");
response.setContentType("text/html;charset=UTF-8");

for (int j = 0; j < list.size(); j++) {

EmpT empt = new EmpT();
empt = list.get(j);

HSSFRow row = sheet.createRow(j + 1);
HSSFCell c0 = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
HSSFCell c1 = row.createCell(1, HSSFCell.CELL_TYPE_STRING);
HSSFCell c2 = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
HSSFCell c3 = row.createCell(3, HSSFCell.CELL_TYPE_STRING);
HSSFCell c4 = row.createCell(4, HSSFCell.CELL_TYPE_STRING);

c0.setCellValue(empt.getId());
c1.setCellValue(empt.getName());
c2.setCellValue(empt.getSex());
c3.setCellValue(empt.getEmail());
c4.setCellValue(empt.getDeptName().getdName());
}
FileOutputStream fOut = new FileOutputStream(outputFile);
workbook.write(fOut);
fOut.flush();
fOut.close();
File f = new File(outputFile);
if (f.exists() && f.isFile()) {
try {
FileInputStream fis = new FileInputStream(f);
URLEncoder.encode(f.getName(), "utf-8");
byte[] b = new byte[fis.available()];
fis.read(b);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + createExcelname + "");
ServletOutputStream out = response.getOutputStream();
out.write(b);
out.flush();
out.close();
if (fis != null) {
fis.close();
}
f.delete();
message = "success";
} catch (Exception e) {
e.printStackTrace();
}
}
return message;
}

5,关键代码到此完成,运行一下看看:

选择excel导入,服务端就会将excel中的数据读取插入到数据库中,

Excel文件:

数据库:

项目结束,excel文件数据成功导入的数据库中。

获取更多教程,请持续关注我的博客。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: