具体就是把Excel中的内容设值到model中。在列表中展示。字段要对应。
不是上传文件。不是上传文件。不是上传文件。
//QuoteProductController.java
/**导入报价产品
*/
@RequestMapping(value="/importData.do")
@ResponseBody
public String importData(SolutionProductImportModel model ,HttpServletRequest request ,HttpServletResponse response) throws Exception{
String filename = model.getFile().getOriginalFileName();//model中file类型为 MultipartFile,要导入的文件。
String fileType = filename.substring(model.getFile().getOriginalFilename().lastIndexOf(".")); //就是截取 [ .+后面的]
try{
if(".xls".equals(fileType)){
//导入前,删除当前报价下的所有产品信息
importMapper.delete(model.getQuoteId());
//导入--读取excel内容到model中
List<String> errorList = new LinkedList<String>();//用来装自定义的错误信息?
List<SolutionProductImportModel> list = readExcel(model.getFile().getInputStream(), model.getQuoteId(), errorList);
if(errorList.isEmpty()){ //读取excel信息到model的过程中没有错误发生。说明导入成功
if(list.size() > 0){
importMapper.importDatas(list);
return StringUtils.resultSuccessToJson("导入成功!");
}
errorList.add("无可导入的数据"); //说明没数据
}
return StringUtils.resultFailToJson(errorList); //读取excel信息到model的过程中有错误发生,导入失败。
}else{ //说明文件格式不是”.xls“
return StringUtils.resultFailToJson("您上传的文件格式有误,请上传xls格式的文件!");
}
}catch(Exception e){
return StringUtils.resultFailToJson(e);
}
//读取Excel内容到model中
public static List<SolutionProductImportModel> readExcel(InputStream is ,String quoteId,list<String> errorList)throws Exception{
//创建一个excelList 用来存储读取的内容
List<SolutionProductImportModel> excelList = new LinkedList<>();
//获取Excel文件对象
Workbook wb = Workbook.getWorkbook(is);
try{
//获取文件的指定工作表 默认的第一个
Sheet sheet = wb.getSheet(0);
Cell cell1 = ExcelUtils.getCellByValue(sheet,"物料号");
Cell cell2 = ExcelUtils.getCellByValue(sheet,"数量");
Cell cell3 = ExcelUtils.getCellByValue(sheet,"意向单价");
Cell cell4 = ExcelUtils.getCellByValue(sheet,"质保期");
if(cell1 == null || cell2 == null || cell3 == null || cell4 == null ){
errorList.add("模板格式不正确"); //如果获取的第一张表的对应的格子是空的,就说明模板有问题。
return excelList;
}
int row_i = cell1.getRow() +1;
/*************循环开始**********/
for(int i = row_i ; ; i++){ //没有结束条件语句
StringBuffer error = new StringBuffer();
Cell val1 = sheet.getCell( cell1.getColumn(), i );
if(StringUtils.isBlank(val1.getContents())){break;} //物料号列 --遍历直到cell内容值为空
Cell val2 = sheet.getCell( cell2.getColumn(), i );
if(! "".equals(val2.getContents())){
Integer num = Integer.parseInt(val2.getContents());
if(num < 0 ){error.append("[数量]必须为正数!");} //数量列 --在能循环的条件下【数量必填】
}else{
error.append("[数量]必填!");
}
Cell val3 = sheet.getCell(cell3.getColumn(),i);
if(!"".equals(val3.getContents())){
//判断当前数据是否为正数0-9
Double.parseDouble(val3.getContents());
if(error.length() > 0 ) error.append(",");
error.append("[意向单价]必须为正数"); //这一步是不是少了什么?/还是不需要做?
}
Cell val4 = sheet.getCell(cell4.getColumn(),i);
if(!"".equals(val4.getContents())){
//判断当前数据是否为正数0-9
Double.parseDouble(val4.getContents());
if(error.length() > 0 ) error.append(",");
error.append("[质保期]必须为正数"); //这一步是不是少了什么?/还是不需要做?
}
if(error.length() > 0 ){
errorList.add(String.format("行号[%d]:%s",i+1,error.toString()));
continue;
}
SolutionProductImportModel model = new SolutionProductImportModel(); //设值
model.setMaterialNum(val1.getContents());//物料号设值
model.setQuantity(Integer.parseInt(val2.getContents()));//数量
model.setUnitpri(val3.getContents());//意向单价
model.setWarranty(val4.getContents());//质保期
model.setQuoteId(quoteId);//报价Id--应该都是一样的,也就是父Id.
model.setId(Get32Primarykey.newErpCode()); //记录Id
model.setUserId(SystemUtils.getUserModel().getRowId());//和当前登录用户绑定。谁导入的就知道了。
excelList.add(model);
}
/*************循环结束**********/
return excelList;
}finally{
wb.close();
}
}
}//类尾
AttachmentServiceImpl
//ftp上传文件,东西非常多
AttachmentModel:(extends BaseModel)
String type;//模块
String filename;//上传文件名字
String ftppath;//ftp路径
String partyId;//父Id
MultipartFile uploadFile; //要上传的文件
/**附件信息
*/
@Service
public class AttachmentServiceImpl extends AbstractBase<AttachmentModel> implements AttachmentService{
protected static final Logger log = LoggerFactory.getLogger(AttachmentServiceImpl .class);
public Map<String,String> getRawMapping(){
Map<String,String> map = new LinkedHashMap<String,String>();
map.put("SHYY File Type","type");//模块
map.put("File Name","fileName");//上传文件名称
map.put("File Path","ftppath");//FTP路径
map.put("Parent Id","partyId");//模块
return map;
}
@Override
public String getBusinessComponeseName(){
return "DH Platform FTP Attachment Url";
}
@Override
public String getBusinessObjectName(){
return "DH Platform Attachment";
}
@Override
public String getListExpress(Attachment model){
List<String> list = new LinkedList<String>();
super.addRowIdsExpr(list,model);
return getExpress(list);
}
//上传附件
public void createFS(String FsUrlId, String sFileType,String sParentId,String...values)throws Exception{
if(StringUtils.isBlank(FsUrlId)){throw new ExceptionWithCode("0008");} //rowId没有提供
if(StringUtils.isBlank(sFileType)){throw new ExceptionWithCode("0014");} //类型没有提供
Map<String,String> param = new ConcurrentHashMap<String,String>();
param.put("FsUrlId",FsUrlId);//当前记录Id
param.put("sFileType",sFileType);//模块名称
param.put("sParentId",sParentId);//父Id
//处理可变参数。
int i = 0;
for(String value : values){
i++;
if(value == null ){
param.put(String.format("sValue%d",i),"");
}else{
param.put(String.format("sValue%d",i),value);
}
Map<String,String> retMap = super.invokeBs("DH Platform Upload Attachment Service","CreateFS",param);
}
}//上传方法尾
//下载附件
public String uploadFTP(String FsUrlId, String sFileType, String sParentId)throws Exception{
Map<String,String > param = new ConcurrentHashMap<>();
param.put("FsUrlId",FsUrlId);//当前记录Id
param.put("sFileType",sFileType);//模块名称
param.put("sParentId",sParentId);//父Id
//调用BS的下载方法
Map<String ,String > retMap = super.invokeBs("DH Platform Upload Attachment Service","UploadFTP",param);
if(!retMap.containsKey("uFileUrl")){
throws new ExceptionWithCode("oppty.0004");//附加从Siebel 上传到FTP失败。
}
return retMap.get("uFileUrl");
}
//这个是用来存放ftp文件的集合,记录着文件的路径
public static final Map<String ,String> dirMap = new ConcurrentHashMap<>();
public static final String getDir(String type)throws Exception{
if(dirMap.isEmpty() || !dirMap.containsKey(type)){
//key就是sFileType,本地可以根据该映射找到ftp上文件。
dirMap.put("客户-附件","/crm/Account");
dirMap.put("商机-附件","/crm/Opportunity");
dirMap.put("QuoteAtt","/crm/QuoteAtt"); //报价附件
dirMap.put("BiddingAtt","/crm/BiddingAtt");//招投标附件
dirMap.put("OrderAtt","/crm/OrderAtt"); //订单附件
dirMap.put("AgreementUnbid","/crm/AgreementUnbid"); //合同下非标申请
dirMap.put("AccntUnbid","/crm/AccntUnbid"); //客户下非标申请
}
if(!dirMap.containsKey(type)) throws new Exception("不支持的附件类型,请在ftp上创建附件类型");
return dirMap.get(type);
}
@Override
public Map<String,String> upload(String partyId, String rowId,String type,MultipartFile file,String...values) throws Exception{
Map<String,String> map = new LinkedHashMap<String,String>();
if( null == file )return map;
String fileName = null;
String path = null;
if( file != null && file.size() >0){
//上传了文件,更新FTP上的文件。取文件名称以及上传到FTP的路径
fileName = file.getOriginalFielname();
String fileType = fileName.subString(fileName.lastIndexOf("."));//[.xxx]
fileName = StringUtils.getUUID19()+partyId+fileType;//设置新文件名
InputStream is = file.getInputStream();
path = fileService.upload(getDir(type),fielName,InputStream);//获取上传后的路径
log.info("upload method 上传后文件路径:"+path);
}
}
}//类尾
FileServiceImpl/******************************/
FtpServerModel :(implements Serializable)
int idx; //序号
int port; //端口号
String hostname;//主机名
String username;//用户名
String password;//密码
String root; //根路径
Date alertDate;//警告日期
//特殊get方法
boolean error = false;
public boolean isError(){
return error;
}
//记得提供有参构造
@Service
public class FileServiceImpl implements FileService{
public static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
public static final List<FtpServerModel> ftplist = new java.util.concurrent.CopyOnWriteArrayList<FtpServerModel>();
public static final Object syncObject = new Object();
//1:获取ftp服务模型
public static final synchronized FtpServerModel getFtpServerModel(){
List<FtpServerModel> serverlist = getOKServers(); //师父亲,你怎么又双封装方法了!!
if(serverlist == null || serverlist.isEmpty()) throw new RuntimeException("无可连接的FTP服务器");
Collections.sort(serverlist,new Comparator<FtpServerModel>(){
@Override
public int compare(FtpServerModel o1,FtpServerModel o2){ return o1.getIdx() - o2.getIdx();} //无法理解
}
);
for(FtpServerModel server : serverlist){
return server;
}
throw new RuntimeException("无可连接的FTP服务器");
}
//获取可用服务器
private static List<FtpServerModel> getOKServers(){
List<FtpServerModel> serverlist = new ArrayList<>();
Collection<FtpServerModel> list = getServers(); //又封装方法
for( FtpServerModel s : list ){
if(s.isError()){
continue;
}
serverlist.add(s);
}
return serverlist;
}
//获取服务器
public static Collection<FtpServerModel> getServers(){
if(ftplist.isEmpty()){
synchronized(ysncObjec){
if(ftplist.isEmpty()){
String serverStr = PropertiesUtil.getAppContext("ftp.server.list"); //这个找到 environments(和webapp同级)下的config_*.properties
//*=uat值为:10.1.1.191|21|ftpuser|Uiop&098|/home/ftpuser(#FTP IP,端口,用户名,密码,root目录)
//*=pro值为:10.1.82.95|21|ftpuser|P#dxsmg2017|/home/ftpuser,10.1.82.94|21|ftpuser|P#dxsmg2017|/home/ftpuser
if(StringUtils.isBlank(serverStr))return ftplist;
//获取到ftp服务器列表
String[] serverItems = serverStr.split(",");
int idx = 0;
for (String serverItem :serverItems){
String[] servercfgs = ServerItem.split("\\|"); // [10.1.1.191, 21, ftpuser, Uiop&890,/home/ftpuser]
if(servercfgs.length != 5 ) continue;
idx ++;
FtpServerModel server = new FtpServerModel(idx,servercfgs[0],servercfgs[1],servercfgs[2],servercfgs[3],servercfgs[4]);
//所以可以看出来,这里 idx,只是服务器列表的 序号。还要记得写 有参构造哦,model中。
ftplist.add(server);
}
}
}
}
return ftplist;
}
//获取ftp客户端
public static final FTPClient getFTPClient() throws Exception{
FTPServerModel model = getFtpServerModel(); //fengzhuang
return FtpUtils.getConnectionFTP(model.getHostname(),model.getPort(),model.getUsername(),model.getPassword());
}
@Override
public String upload(String path,String fileName,InputStream is)throws Exception{
FtpServerModel model = getFtpServerModel(); //封装方法
FTPClient ftp = getFTPClient(); //又 封装方法
//上传文件,FTP客户端
FtpUtils.uploadFile(ftp,String.format("%s%s",model.getRoot(),path),filename.is);
//返回ftp上完整路径。ip,端口号,使用ftp客户端获取。
return String.format("ftp://%s:%d%s/%s",StringUtils.getIpAddress(ftp.getRemoteAddress()),ftp.getRemotePort(),path,fileName);
}
}//类尾