今天给大家带来的是文件上传中比较常用的,上传excel文件,将表格中的数据存入数据库中的一个转化的工具类;大致的流程是:前端点击上传按钮-->选择需要上传的excel表格-->确认上传--> 文件传到后台-->后台处理file文件-->将文件转化成List-->将List集合存入数据库
首先通过前端点击按钮:
点击导入按钮,触发input框点击事件:
$('#input').click(function () {
$('#import_modal').modal('show');
})
点击按钮后,弹出框:
弹窗代码:
选择要上传的文件,然后点击确定:
点击确定触发:将请求地址改成自己本地的
$('#import_modal form').bootstrapValidator('destroy');
$('#import_modal form').bootstrapValidator({
message: '输入不合法',
fields: {
file: {
validators: {
notEmpty: {message: '文件不能为空'}
}
}
}
}).on('success.form.bv', function (e) {
var files = $("#file").get(0).files;
if (files.length > 0) {
if (files[0].size > 1024 * 1024 * 100) {
alert('文件大小不能超过100MB');
return false;
}
var formData = new FormData();
formData.append('file', files[0]);
$.ajax({
url:
'${pageContext.request.contextPath}/backend/form/evaluation_update/import',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false,
dataType: "json",
beforeSend: function () {
$('#import').button('loading');
},
success: function (data) {
if (data.errorCode === 0) {
alert(data.message);
$('#import_modal').modal('hide');
location.reload();
} else {
alert(data.message);
}
$('#import').button('reset');
}, error: function () {
$('#import').button('reset');
}
});
}
});
请求到后台:
poi依赖
org.apache.poi
poi
3.14
org.apache.poi
poi-ooxml
3.14
controller层
@RequestMapping("evaluation_update/import")
@ResponseBody
public Result evaluationUpdate(@RequestParam(value = "file", required = true) MultipartFile file,
UserSession session) throws Exception {
try {
Result result = new Result();
result.setMessage("导入成功");
int count = wfOrderService.importAnnualDemand(session, file);
result.setMessage(count > 0 ? "导入成功,共:" + count + "条记录!" : "本次导入0条数据!");
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
service层:
public int importAnnualDemand(UserSession session, MultipartFile file) throws ErrorCodeException {
List
POIExcelUtil.readExcel工具类代码(拷贝即用):
//包名
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 java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class POIExcelUtil {
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
private static NumberFormat numberFormat = NumberFormat.getNumberInstance();
static {
numberFormat.setGroupingUsed(false);
}
public static List readExcel(File file, int firstRowNum, boolean needTitle) throws IOException {
// 检查文件
checkFile(file);
Workbook workBook = getWorkBook(file);
// 返回对象,每行作为一个数组,放在集合返回
ArrayList rowList = new ArrayList<>();
if (null != workBook) {
// 获得当前sheet工作表
Sheet sheet = workBook.getSheetAt(0);
if (sheet != null) {
// 获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
sheet.getSheetName();
int firstCellNum = sheet.getRow(firstRowNum - 1).getFirstCellNum();
int lastCellNum = sheet.getRow(firstRowNum - 1).getLastCellNum();
if (lastCellNum > 200) {
lastCellNum = 200;
}
if (needTitle) {
// 获取标题行,并返回在第一个list元素
Row titleRow = sheet.getRow(firstRowNum - 1);
String[] titleCells = new String[lastCellNum];
// 循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = titleRow.getCell(cellNum);
titleCells[cellNum] = getOriginalCellValue(cell);
}
rowList.add(titleCells);
}
// 循环所有行数据
for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
// 获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
String[] cells = new String[lastCellNum];
// 循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getOriginalCellValue(cell);
}
rowList.add(cells);
}
}
workBook.close();
}
return rowList;
}
public static List readExcelPrecision(File file, int firstRowNum) throws IOException {
// 检查文件
checkFile(file);
Workbook workBook = getWorkBook(file);
// 返回对象,每行作为一个数组,放在集合返回
ArrayList rowList = new ArrayList<>();
if (null != workBook) {
// 获得当前sheet工作表
Sheet sheet = workBook.getSheetAt(0);
if (sheet != null) {
// 获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
sheet.getSheetName();
int firstCellNum = sheet.getRow(firstRowNum - 1).getFirstCellNum();
int lastCellNum = sheet.getRow(firstRowNum - 1).getLastCellNum();
if (lastCellNum > 200) {
lastCellNum = 200;
}
// 循环所有行数据
for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
// 获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
String[] cells = new String[lastCellNum];
// 循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getOriginalCellValuePrecision(cell);
}
rowList.add(cells);
}
}
workBook.close();
}
return rowList;
}
public static List
service注入一个上传类:
@Autowired
private UploadManager uploadManager;
上传工具类(拷贝即用):
import com.yogapay.core.LangUitls;
import com.yogapay.sql.mapping2.StringListSQLData;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
public class UploadManager implements InitializingBean {
public static final String PATH_PREFIX = "/uploads";
private final String basePath;
private final String[] dirNames;
@Autowired(required = false)
private ServletContext sc;
//
private File baseDir;
private URI baseDirUri;
private Map dirs;
public UploadManager(String basePath, String dirNames) {
this.basePath = StringUtils.trimToNull(basePath);
this.dirNames = dirNames.split("\\s+");
}
@Override
public void afterPropertiesSet() throws Exception {
if (sc == null) {
baseDir = new File("target");
} else {
baseDir = new File(basePath == null ? sc.getRealPath("uploads") : basePath);
}
baseDirUri = baseDir.toURI();
dirs = new HashMap();
for (String dir : dirNames) {
dirs.put(dir, createDir(dir));
}
dirs = Collections.unmodifiableMap(dirs);
}
private File createDir(String name) {
File t = new File(baseDir, name);
if (!t.mkdir() && !t.exists()) {
throw new RuntimeException(t.getAbsolutePath());
}
return t;
}
public File file(String src) {
if (!src.startsWith(PATH_PREFIX)) {
throw new IllegalArgumentException();
}
src = src.substring(PATH_PREFIX.length());
if (src.isEmpty() || src.charAt(0) != '/') {
throw new IllegalArgumentException();
}
return new File(baseDirUri.resolve(src.substring(1)));
}
public String src(File f) {
URI uri = baseDirUri.relativize(f.toURI());
if (uri.isAbsolute()) {
throw new IllegalArgumentException();
}
return PATH_PREFIX + "/" + uri;
}
public StringListSQLData saveDailyFiles(File rdir, Date date, MultipartFile[] files, String prefix, String suffix) throws IOException {
if (files == null) {
return null;
}
File dir = LangUitls.dailyFile(rdir, date);
StringListSQLData fileList = new StringListSQLData();
for (MultipartFile img : files) {
if (!img.isEmpty()) {
File f = File.createTempFile(prefix, suffix, dir);
img.transferTo(f);
fileList.add(src(f));
}
}
return fileList;
}
public File getBaseDir() {
return baseDir;
}
public Map getDirs() {
return dirs;
}
}
StringListSQLData:
public class StringListSQLData extends ArrayList implements SQLDataConvertible {
public StringListSQLData(int initialCapacity) {
super(initialCapacity);
}
public StringListSQLData() {
}
public StringListSQLData(Collection extends String> c) {
super(c);
}
@Override
public void toSQLData(PreparedStatement pstmt, int index) throws SQLException {
Element eArray = DocumentHelper.createElement("List");
for (String t : this) {
Element eValue = DocumentHelper.createElement("value");
eValue.setText(t == null ? "" : t);
eArray.add(eValue);
}
pstmt.setString(index, eArray.asXML());
}
@Override
public boolean fromSQLData(ResultSet rs, int index) throws SQLException {
String xml = rs.getString(index);
if (rs.wasNull()) {
return false;
}
try {
Document doc = DocumentHelper.parseText(xml);
for (Iterator iterator = doc.getRootElement().elementIterator("value"); iterator.hasNext();) {
Element next = iterator.next();
this.add(next.getText());
}
} catch (DocumentException ex) {
throw new SQLException("\r\n" + xml, ex);
}
return true;
}
获取文件地址:
public String getFilePath(MultipartFile file) throws IOException {
MultipartFile[] files = {file};
String targetDir = uploadManager.getBaseDir() + "/" + "";
int index = file.getOriginalFilename().lastIndexOf(".");
String ext = index > 0 ? file.getOriginalFilename().substring(index + 1) : "";
StringListSQLData fileData = uploadManager.saveDailyFiles(new File(targetDir), new Date(), files, "file_", "." + ext);
return fileData.get(0);
}
最后在Mybatis中将对应映射的sql写好就行了哦
INSERT IGNORE INTO 表名(字段名)
VALUES
(#{i.属性名})
最后导入成功:
今天的分享结束啦,谢谢大家哦~~