excel的导入导出 以及将数据存入到MySQL
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>客户管理</title>
<!--jqueyr-->
<script src="/jq/jquery.min.js"></script>
<!--添加异步 上传 的js框架 支持加载-->
<script src="/AjaxFileUpload/ajaxfileupload.js"></script>
</head>
<input type="file" id="file" name="file" onchange ="uploadFile(this)" ></input>
<!--文件上传js-->
<script>
function uploadFile(file){
alert("==========1");
$.ajaxFileUpload({
url : '/sgl/upload_excel', //用于文件上传的服务器端请求地址
secureuri : false, //一般设置为false
fileElementId : 'file', //文件上传空间的id属性 <input type="file" id="file" name="file" />
type : 'post',
dataType : 'text', //返回值类型 一般设置为
success : function(result) //服务器成功响应处理函数
{
var result = $.parseJSON(result.replace(/<.*?>/ig,""));
alert(result.msg);
layer.closeAll();
},
error : function(result)//服务器响应失败处理函数
{
}
});
alert("==========2");
return false;
}
</script>
</html>
controller代码
请修改文件路径
package com.example.controller;
import com.example.util.DateUtil;
import com.example.util.ExcelUtil;
import com.example.util.ResponseUtil;
import com.example.util.TestUser;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Author: SGL
* Created by Administrator on 2019/12/2.
*/
@Controller
@RequestMapping("/sgl")
public class MyController {
@RequestMapping("/index")
public String index(HttpServletRequest request){
String contextPath = request.getContextPath();
request.setAttribute("ctx",contextPath);
return "myIndex";
}
/**
* 接受文件 解析 上传资料。
*
*/
@ResponseBody
@RequestMapping("/upload_excel")
public JSONObject upload_excel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception {
/*
1 . 文件上传
*/
JSONObject result = new JSONObject();
System.out.println(file.getOriginalFilename());
if(!file.isEmpty()){
String webPath=this.getClass().getClassLoader().getResource("").getPath();
String filePath= "/static/upload_file/excel/";
//把文件名子换成(时间搓.png)
// String imageName="houtai_logo."+file.getOriginalFilename().split("\\.")[1];
String fileName= DateUtil.formatDate(new Date(), "yyyyMMdd-HHmmssSSS")+"_"+file.getOriginalFilename();
//FileUtil.makeDirs(webPath+filePath);
//保存服务器
//file.transferTo(new File(webPath+filePath+fileName));
file.transferTo(new File("/D:\\sgl\\softwareForWork\\mytest\\excel_import_export\\src\\main\\resources\\static\\upload_file\\excel\\"+fileName));
//2 . excel导入 到MySQL数据库中
//解析分区表
int cnt=0;
// 声明Connection对象
Connection con;
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名 test
String url = "jdbc:mysql://URL指向要访问的数据库名/luckymoney?serverTimezone=UTC";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "你的密码";
try {
Class.forName(driver);
// 1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed())
System.out.println("\n\t\t成功以 " + user + " 身份连接到数据库!!!");
String sql = "INSERT INTO kd(name_cn,kd_code) VALUES(?,?)";
java.sql.PreparedStatement ptmt = null;
con.setAutoCommit(false);// 关闭事务
ptmt = con.prepareStatement(sql);
List list = new ArrayList();
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(new File("/D:\\sgl\\softwareForWork\\mytest\\excel_import_export\\src\\main\\resources\\static\\upload_file\\excel\\" + fileName)));
HSSFWorkbook wb = new HSSFWorkbook(fs);
//获取第一个sheet页
HSSFSheet sheet = wb.getSheetAt(0);
if (sheet != null) {
//从第四行开始读取
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
HSSFRow row = sheet.getRow(rowNum); //每一行的数据
if (row == null) {
continue; //读完了
}
//拿到当前这一行数据的第1个单元格数据
String name = ExcelUtil.formatCell(row.getCell(0));
String code = ExcelUtil.formatCell(row.getCell(1));
System.out.println(name + "==" + code);
try {
ptmt.setString(1,name);
ptmt.setString(2,code);
ptmt.addBatch();
} catch (Exception e) {
cnt++;
e.printStackTrace();
}
try {
ptmt.executeBatch();//执行给定的SQL语句,该语句可能返回多个结果
con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println(cnt);
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//解析
//删除用过的文件
//FileUtil.deleteFile("/G:/zhiyun/learn_excel_output/src/main/resources/static/upload_file/excel/"+fileName);
// 删除用过的文件
/*
3 . excel导出
*/
//查询数据库,返回数据
//ArrayList<Object>=service.queryMath();
//ArrayList<User>=service.queryMath();
ArrayList<TestUser> objects = new ArrayList<>();
objects.add(new TestUser().setId(1).setName("hhhhh"));
objects.add(new TestUser().setId(3).setName("aaaaa"));
Workbook wb = null ;
try {
//导入数据的xls模板 (新建一个xls, 开头标题写好 . 之后从第2行开始填充数据)
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("/D:\\sgl\\softwareForWork\\mytest\\excel_import_export\\src\\main\\resources\\static\\upload_file\\excel\\20191130-155739057_sgl.xls"));
wb = new HSSFWorkbook(fs);
// 取得 模板的 第一个sheet 页
Sheet sheet = wb.getSheetAt(0);
// 拿到sheet页有 多少列
int cellNums = sheet.getRow(0).getLastCellNum();
// 从第1行 开搞 下标1 就是第2行
int rowIndex = 110;
Row row ;
ResponseUtil.export(response,wb,"客户.xls"); // 导出成功后重命名为客户.xls文件自动让客户下载
} catch (IOException e) {
e.printStackTrace();
}
}
result.put("success", true);
result.put("msg", "导入成功");
return result;
}
}