Excel导入的MySQL的方法:
浏览器选择excel文件,传至服务端,在服务端解析此excel并将数据导入到数据库中。
源码下载
这里只保存关键代码,详细的源代码可点击上面源码下载前往下载
1,项目结构:
2,导入页面:
jsp:
js:
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:
@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 list = excelService.OutputExcel();
String message = OutputExcel.OutExcel(request, response, list);
if (message.equals("fail")) {
ServletOutputStream out = response.getOutputStream();
message = "导出失败,请重试";
String s = "";
out.print(s);
}
return null;
}
service:
@Override
public String InputExcel(InputStream is, String originalFilename) {
Map ginsengMap = new HashMap();
List> list;
if (originalFilename.endsWith(".xls")) {
list = Excel.readExcel2003(is);
} else {
list = Excel.readExcel2007(is);
}
for (int i=0,j=list.size();i 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 OutputExcel() {
return excelMapper.getAll();
}
mapper.xml:
insert into wei.emp_t (name,sex,email,dept_id) values
(#{name },#{sex },#{email },#{dept_id },)
e.id, e.name, e.sex, e.email, e.dept_id, d.d_id, d.d_name
and ${criterion.condition}
and ${criterion.condition} #{criterion.value}
and ${criterion.condition} #{criterion.value} and
#{criterion.secondValue}
and ${criterion.condition}
#{listItem}
4,解析excel的工具类:
excel文件传至服务端:
public static String upload(HttpServletRequest request, HttpServletResponse response) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(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 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文件:
public static ArrayList> readExcel2003(InputStream is) {
try {
ArrayList> rowList = new ArrayList>();
ArrayList
导出数据到excel并在浏览器下载:
public static String OutExcel(HttpServletRequest request, HttpServletResponse response, List 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文件数据成功导入的数据库中。
获取更多教程,请持续关注我的博客。