java 上传Excel文件导入数据

Posted k142857

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 上传Excel文件导入数据相关的知识,希望对你有一定的参考价值。

/**
* 上传文件分为几步
* 1-获取用户上传的文件Excel
* 2-读取Excel文件内容
* 3-数据转成实体
*/


package com.csot.util;

import com.csot.pm.file.model.FileEntity;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 导入Excel 工具类
* Created by csot.qhluodajie on 2018/4/18.
*/
public class ImprotExcelUtil {

public static Workbook checkExcel(FileEntity fileEntity) throws Exception{
Workbook workbook = null;
// 判断文件类型
if (fileEntity.getFileType().equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(fileEntity.getInputStream());
} else if (fileEntity.getFileType().equalsIgnoreCase("xlsx")) {
//workbook = new XSSFWorkbook(fileEntity.getInputStream());
workbook = WorkbookFactory.create(fileEntity.getInputStream());
} else {
throw new RuntimeException("上传文件格式不正确!");
}
return workbook;
}

/**
* 数据转成List<Map>
* @param sheet 流
* @param cellName 对象数据列,和实体字符一样
* @param rowNum 从第几行开始
* @param cellNum 从第几列开始
* @return 返回List<Map>
*/
public static List<Map<String,Object>> excelToListMap(Sheet sheet,int rowNum,int cellNum,String [] cellName){
List<Map<String,Object>> listMap =new ArrayList<>();
for (int i = rowNum; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Map<String,Object> map = new HashMap<>();
for(int v=cellNum;v<row.getLastCellNum();v++){
Object obj = row.getCell(v);
if(obj != null){
row.getCell(v).setCellType(Cell.CELL_TYPE_STRING);
map.put(cellName[v],row.getCell(v).getStringCellValue());
}else {
map.put(cellName[v],"");
}

}
listMap.add(map);
}
return listMap;
}
public static String objFromJson(Object obj){
Gson gson = new Gson();
return gson.toJson(obj);
}
public static <T> T fromJson(String json,Class<T> type){
Gson gson = new Gson();
return gson.fromJson(json,type);
}
public static <T> List <T> listFromJson(String json,Type type){
Gson gson = new Gson();
return gson.fromJson(json,type);
}

}
//业务层
@Override
public void saveImprotMaterial(Workbook workbook) throws Exception {
   //导入数据列数,与实体字符一样
String[] cellName = {"materialName", "factoryName", "actualRate", "targetRate", "quarterTargetRate", "quarterName"};
   //SheetAt 位置,和第几行几列开始
List<Map<String, Object>> listMap = ImprotExcelUtil.excelToListMap(workbook.getSheetAt(0),1,0, cellName);
  //转实体
List<PmMaterialRate> list = ImprotExcelUtil.listFromJson(ImprotExcelUtil.objFromJson(listMap),new TypeToken<List<PmMaterialRate>>(){}.getType());
for(PmMaterialRate pmMaterialRate :list){
//TODO 保存操作
    //...
}
}
//控制层
@RequestMapping("saveAllImprot")
@ResponseBody
public AjaxRtnJson saveAllImprot(String factoryName, String sheetAt, HttpServletRequest request) {
try {
List<FileEntity> list = FileUtils.getFilesFromRequest(request);
if (list == null || list.size() == 0) {
return new AjaxRtnJson(false, "保存失败!");
}
FileEntity fileEntity = list.get(0);
Workbook workbook = ImprotExcelUtil.checkExcel(fileEntity);
      this.pmMaterialLightCrystalServiceImpl.saveImprot(workbook);//cu酮酸

    }catch (Exception ex) {
    
  
    }


}


//文件工具类
//从request中提取上传的文件列表
package com.csot.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.csot.pm.file.model.FileEntity;

public class FileUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

/**
* 从request中提取上传的文件列表
*
* @param request HttpServletRequest
*/
public static List<FileEntity> getFilesFromRequest(HttpServletRequest request) {
List<FileEntity> files = new ArrayList<FileEntity>();

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
try {
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
InputStream inputstream = entity.getValue().getInputStream();
if (!(inputstream.markSupported())) {
inputstream = new PushbackInputStream(inputstream, 8);
}

String fileName = entity.getValue().getOriginalFilename();
String prefix =
fileName.lastIndexOf(".") >= 1 ? fileName.substring(fileName.lastIndexOf(".") + 1)
: null;
FileEntity file = new FileEntity();
file.setInputStream(inputstream);
file.setFileType(prefix);
file.setFileName(fileName);
files.add(file);
}
} catch (IOException e) {
e.printStackTrace();
}
return files;
}

/**
* 下载文件
*
* @param response
* @param entity的filePath 需要绝对全路径
*/
public static void setDownloadResponse(HttpServletResponse response, FileEntity entity)
throws IOException {
if (entity == null || response == null) {
response.sendError(404, "File not found!");
return;
}

File f = new File(entity.getFilePath());
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
/*
* if (isOnLine) { // 在线打开方式 URL u = new URL("file:///" + filePath);
* response.setContentType(u.openConnection().getContentType());
* response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); //
* 文件名应该编码成UTF-8 } else { // 纯下载方式
*/
response.setContentType("application/x-msdownload");
response.setHeader(
"Content-Disposition",
"attachment; filename="
+ URLEncoder.encode(entity.getFileName(), "utf-8").replace("+", "%20"));
// }
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0) {
out.write(buf, 0, len);
}
br.close();
out.close();
}


/**
* 保存文件
*
* @param path 路径
* @param content 内容
*/
public static void write(String path, String content) {
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
// out.write("\n"+content);
out.write(content);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 删除文件
*
* @param path 路径
*/
public static void delete(String path) {
File file = new File(path);
if (file.exists()) {
file.delete();
}
logger.info("delete file:" + path);
}

/**
* 删除某路径下所有文件
*
* @param path 路径
*/
public static void deleteAllFiles(String path) {
File dirFile = new File(path);
if (!dirFile.exists() || !dirFile.isDirectory()) {
return;
}
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
delete(files[i].getAbsolutePath());
}
}
}

/**
* 拷贝文件
*/
public static void copyFile(String fromPath, String destPath) {
File oldfile = new File(fromPath);
File newfile = new File(destPath);
if (!oldfile.exists()) {
throw new RuntimeException("文件不存在!");
}
if (newfile.exists()) {
newfile.delete();
} else if (!newfile.getParentFile().exists()) {
newfile.getParentFile().mkdirs();
}

// int bytesum = 0;
int byteread = 0;
try { // 文件存在时
InputStream inStream = new FileInputStream(fromPath); // 读入原文件
FileOutputStream fs = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
// bytesum += byteread; // 字节数 文件大小
fs.write(buffer, 0, byteread);
}
fs.close();
inStream.close();
} catch (Exception e) {
throw new RuntimeException("复制单个文件操作出错!");
}
}

}















































































































































































































































































































以上是关于java 上传Excel文件导入数据的主要内容,如果未能解决你的问题,请参考以下文章

java怎么把excel文件导入到web网页上显示

怎样将Excel文件导入数据库(在JSP环境下Java代码)

记录-java(jxl) Excel导入数据库

java中怎么让导入的excle表中每一条数据对应文件夹中对应的图片

java实现导入动态excel

把excel导入服务器后台页面显示,java怎么写啊,求答案,最后的效果是下图这样。