/**
*上传图片
*/
public String uplodeFile(HttpServletRequest request,MultipartFile file1){
try {
//获取web容器根路径
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath.replace("\\", "/");
//先判断路径是否存在,如果不存在就创建
File file = new File(filePath + WebConstants.UPLOAD_MEMBER_DIR + "temp");
if(!file.exists() && !file .isDirectory()) {
file.mkdirs();
}
String ext = file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf(".") ).toLowerCase();
String fileName=Long.toString(RandomUtils.nextLong())+ext;
File _file=new File(file.getPath()+"/"+fileName);
String fileUrl=WebConstants.UPLOAD_MEMBER_DIR +"temp/"+fileName;
// /*验证图片大小*/
// boolean errorView = pcHandleUploadImageFileException(file1);
// if(errorView){
// return "0";
// }
// /*验证图片格式*/
// errorView=pcUploadImageType(ext);
// if(errorView){
// return "1";
// }
//注意这里的图片后缀不一定是jpg,具体是什么可以从参加中获取的
// file1.transferTo(_file);
FileOutputStream out1 = new FileOutputStream(_file);
IOUtils.copy(file1.getInputStream(), out1);
return fileUrl.replaceAll("\\\\", "/");
} catch (Exception e) {
logger.error("add image",e);
}
return null;
}
/**
* 后台判断图片类型
* @param file
* @param mv
* @return
*/
public boolean pcUploadImageType(MultipartFile file){
String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") ).toLowerCase();
Map<String, Integer> allowTypes=new HashMap<String, Integer>();
allowTypes.put(".bmp", 1);
allowTypes.put(".png", 1);
allowTypes.put(".jpg", 1);
allowTypes.put(".gif", 1);
Integer type=allowTypes.get(ext);
if(type==null){
//mv.addObject("errors", "图片格式只能是(*.jpg, *.png, *.bmp, *.gif)");
return true;
}
else{
return false;
}
}
/**
*
* @param 后台上传图片文件fileSize
* @return
*/
public boolean pcHandleUploadImageFileException(MultipartFile file) {
long fileSize = file.getSize();
//配置的图片最大size
long imagefileMaxSize = Long.valueOf("5242880");//5120KB (1kb=1024bt)
//上传图片大小超过范围
if( fileSize > imagefileMaxSize ){
//String maxSizeDesc = getFileKB(imagefileMaxSize);
return true;
}
else{
return false;
}
}
/**
* 计算KB
* @param byteFile
* @return
*/
protected String getFileKB(long byteFile){
if(byteFile==0)
return "0KB";
long kb=1024;
return ""+byteFile/kb+"KB";
}
/**
*删除图片
*/
public void delete(HttpServletRequest request,String fileUrl) throws Exception {
try {
//获取web容器根路径
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath.replace("\\", "/");
File file = new File(filePath+fileUrl);
if(file.exists()){
boolean d = file.delete();
if(d){
logger.error("delete success");
}else{
logger.error("delete error");
}
}
} catch (Exception e) {
logger.error("delete image",e);
}
}
/**
*拷贝图片
*/
public String copy(HttpServletRequest request,String fileUrl,String filename) throws Exception {
try {
//获取web容器根路径
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath.replace("\\", "/");
// 创建目录
//先判断路径是否存在,如果不存在就创建
File file = new File(filePath + WebConstants.UPLOAD_DIR);
if(!file.exists() && !file .isDirectory()) {
file.mkdirs();
}
<span style="white-space:pre"> </span> //得到文件后缀名
String ext = fileUrl.substring(fileUrl.lastIndexOf(".")).toLowerCase();
filename=filename+ext;
String url2=file.getPath()+"/"+filename;//目标路径
FileInputStream in = new FileInputStream(new File(filePath+fileUrl));//源文件
FileOutputStream out = new FileOutputStream(new File(url2));
String fileUrl2=WebConstants.UPLOAD_DIR +"/";
byte[] buff = new byte[512];
int n = 0;
System.out.println("复制文件:" + "\n" + "源路径:" + fileUrl + "\n" + "目标路径:"
+ url2);
while ((n = in.read(buff)) != -1) {
out.write(buff, 0, n);
}
out.flush();
in.close();
out.close();
System.out.println("复制完成a");
// /*上传到ftp*/
// SysParam param = SysParam.getInstance();
// FTPBean bean = new FTPBean();
// bean.setHost(param.getProperty(SysParam.FTP_SERVER_ADDRESS));
// bean.setPort(Integer.valueOf(param.getProperty(SysParam.FTP_SERVER_PORT)));
// bean.setUsername(param.getProperty(SysParam.FTP_SERVER_USERNAME));
// bean.setPassword(param.getProperty(SysParam.FTP_SERVER_PASSWORD));
// //ftp 跟目录
// String rootDir = param.getProperty(SysParam.FTP_SERVER_DIR);
// //文件路径
// String ftpDir = rootDir+"/"+dir;
// //文件
// File file1 = new File(url2);
// try {
// boolean flag = FTPUtil.uploadFile(ftpDir, filename, file1, bean);
// System.out.println(flag ? "success!!" : "fail !!");
// } catch (Exception e) {
// e.printStackTrace();
// }
// /*---*/
return fileUrl2+filename;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*导出1
*/
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
public @ResponseBody boolean exportExcel(HttpServletResponse response,HttpServletRequest request) {
ServletOutputStream out = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
String filePath =this.getClass().getClassLoader().getResource("templter.xlsx").toString();
filePath = filePath.replace("%20"," ");
filePath = filePath.replace("file:/","");
String outpath = request.getSession().getServletContext().getRealPath("/")+"/upload/";
outpath = outpath.replace("\\", "/");
String name="盈利报表.xlsx";
name = URLEncoder.encode(name, "GB2312");
name = URLDecoder.decode(name, "ISO8859_1");
String outputfile=outpath+name;
File outexl=new File(outputfile);
// 模板路径
copyFile(filePath, outpath, name);
// 读取Excel
FileInputStream file = new FileInputStream(outputfile);
XSSFWorkbook workbook = new XSSFWorkbook(file);
// 第一个sheet
XSSFSheet sheet = workbook.getSheetAt(0);
//查询信息
Map<String, Object> params = new HashMap<String, Object>();
ModelAndView mv = new ModelAndView("");
setupParams(mv, request, params, null, null);
List<ProfitReport> profitReports = reportService.selectByPrimaryKey(params);
int i=2;
Double sum=0.0;
String id="";
int rowsum=0;
for (ProfitReport profitReport : profitReports) {
rowsum++;
if(!profitReport.getId().equals(id)){
sum+=profitReport.getSumBackMoney();
id=profitReport.getId();
}
}
int j=0;
String merchantName="";
for (ProfitReport profitReport : profitReports) {
int row = i + 1 ;
if(!merchantName.equals(profitReport.getMerchantName())){
j++;
}
merchantName=profitReport.getMerchantName();
String [] _profitReport={j+"",profitReport.getMerchantName(),profitReport.getGoodsNo().toString(),
profitReport.getGoodsName(),profitReport.getNum().toString(),profitReport.getMarketPrice().toString(),
profitReport.getMarginRatio().toString(),profitReport.getMarginMoney().toString(),profitReport.getUnitPrice().toString(),
profitReport.getExpectGuessNum().toString(),profitReport.getAdMoney().toString(),profitReport.getPayAdMoney().toString(),
profitReport.getActualGuessNum().toString(),profitReport.getActualAdMoney().toString(),profitReport.getFullBackMoney().toString(),
profitReport.getSumBackMoney().toString(),sum.toString()};
setValues(sheet, row, _profitReport,profitReport,rowsum,workbook);
i++;
}
FileOutputStream os = new FileOutputStream(outputfile);
workbook.write(os);
os.flush();
os.close();
File f = new File(outputfile);
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
response.addHeader("Content-Disposition", "attachment;filename=\""
+ name + "\"");
out = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(out);
while (-1 != (len = bis.read(buf, 0, buf.length))) {
bos.write(buf, 0, len);
}
// response.addHeader("content-type", "application/x-msdownload;");
// response.addHeader("Content-Disposition", "attachment; filename=" + name);
// response.addHeader("content-length", Long.toString(outexl.length()));
// // 向客户端写入文件
// java.io.FileInputStream fin = new java.io.FileInputStream(outexl);
// ServletOutputStream out=response.getOutputStream();
// byte[] b = new byte[1024];
// int j = 0;
// //out.write(new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF});
// while ((j = fin.read(b)) > 0) {
//
// out.write(b);
// }
// fin.close();
} catch (Exception e) {
e.printStackTrace() ;
return false;
}finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
}
}
return true;
}
/**
* 填充值
*
* @param sheet
* @param rownum
* 行
* @param strVal
* 值
* @param num
* 分公司及全网不列入颜色标识中
* @param sort
* 0越大越好 1越小越好(0、1最好最差都有) 2越大越差 3、越小越差 (2、3只有最差) 4不操作
*/
private void setValues(XSSFSheet sheet, int rownum,String[] _profitReport,ProfitReport profitReport,int rowsum,XSSFWorkbook workbook) {
// 得到行
XSSFRow row = sheet.getRow(rownum);
if (null == row) {
row = sheet.createRow(rownum);
}
for (int j = 0; j < _profitReport.length; j++) {
if(profitReport.getCols()>1 && (j==0 || j==1 || j==_profitReport.length-2)){//合并单元格
sheet.addMergedRegion(new CellRangeAddress(rownum, rownum+profitReport.getCols()-1,j,j));
// workbook.createCellStyle().setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
//CellRangeAddress(a,b,c,d) 单元格合并函数:a 单元格的开始行号,b 单元格的结束行号,c 单元格开始列号,d 单元格结束行号
}
if(j==_profitReport.length-1 && rownum==3){//合并单元格
sheet.addMergedRegion(new CellRangeAddress(rownum, rownum+rowsum-1,j,j));
}
XSSFCell cell = row.getCell(j);
if (null == cell) {
cell = row.createCell(j);
}
XSSFCellStyle cellStyle=workbook.createCellStyle();
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(_profitReport[j]);
}
}
/**
* 拷贝模板到指定位子
*
* @throws IOException
*/
public void copyFile(String inputpath, String outpath, String name)
throws IOException {
File path = new File(outpath);
if (!path.exists() && !path.isDirectory()) {
path.mkdirs();
}
FileInputStream fis = null;
FileOutputStream fos = null;
fis = new FileInputStream(inputpath);
fos = new FileOutputStream(outpath + name);
IOUtils.copy(fis, fos);
fos.flush();
fos.close();
}
//导出2
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
public @ResponseBody boolean exportExcel(HttpServletResponse response,HttpServletRequest request) {
//获取web容器根路径
String filePath = request.getSession().getServletContext().getRealPath("/")+"/upload/";
filePath = filePath.replace("\\", "/");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
try {
String outputfile=filePath+RandomUtils.nextLong()+".xls";
File outexl=new File(outputfile);
OutputStream os = new FileOutputStream(outputfile); //:获得文件输出流
WritableWorkbook book = Workbook.createWorkbook(os) ; //:创建一个excel表格
WritableSheet sheet = book.createSheet("第一页", 0) ; //:为excel表格创建一个sheet
Label label =null ;
String[] title = {"商家","商品编号","商品名称","数量","市场价格(元)","保证金比率","保证金(元)","每人广告费","每个产品预计竞猜人数","应预计广告费","实际支付现在","实际竞猜人数","实际广告费(元)","各个产品应退客户金额","合计应退广告费收入"} ;
for (int i = 0; i < title.length; i++) { //:添加表头
label = new Label(i,0,title[i]) ;
sheet.addCell(label) ;
}
//查询信息
Map<String, Object> params = new HashMap<String, Object>();
ModelAndView mv = new ModelAndView("");
setupParams(mv, request, params, null, null);
List<ProfitReport> profitReports = reportService.selectByPrimaryKey(params);
int i=0;
for (ProfitReport profitReport : profitReports) {
int row = i + 1 ;
String [] _profitReport={profitReport.getMerchantName(),profitReport.getGoodsNo().toString(),
profitReport.getGoodsName(),profitReport.getNum().toString(),profitReport.getMarketPrice().toString(),
profitReport.getMarginRatio().toString(),profitReport.getMarginMoney().toString(),profitReport.getUnitPrice().toString(),
profitReport.getExpectGuessNum().toString(),profitReport.getAdMoney().toString(),profitReport.getPayAdMoney().toString(),
profitReport.getActualGuessNum().toString(),profitReport.getActualAdMoney().toString(),profitReport.getFullBackMoney().toString(),
profitReport.getSumBackMoney().toString()};
sheet.setRowView(row, 200);
for (int j = 0; j < _profitReport.length; j++) {
if(profitReport.getCols()>1 && (j==0 || j==9)){//合并单元格
sheet.mergeCells(0,1, 1, 2);
//mergeCells(a,b,c,d) 单元格合并函数:a 单元格的列号,b 单元格的行号,c 从单元格[a,b]起,向下合并的列数,d 从单元格[a,b]起,向下合并的行数
}
sheet.setColumnView(j, 30);
label = new Label(j,row,_profitReport[j]) ;
sheet.addCell(label) ;
}
i++;
}
book.write() ;
book.close() ;
os.close() ;
response.addHeader("content-type", "application/x-msdownload;");
response.addHeader("Content-Disposition", "attachment; filename=" + outexl.getName());
response.addHeader("content-length", Long.toString(outexl.length()));
// 向客户端写入文件
java.io.FileInputStream fin = new java.io.FileInputStream(outexl);
ServletOutputStream out=response.getOutputStream();
byte[] b = new byte[1];
int j = 0;
//out.write(new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF});
while ((j = fin.read(b)) > 0) {
out.write(b);
}
fin.close();
outexl.delete();
} catch (Exception e) {
e.printStackTrace() ;
return false;
}
return true;
}
/**
*下载
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(String fileUrl, HttpServletResponse response,HttpServletRequest request) throws IOException {
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath.replace("\\", "/");
// 构建下载文件的对象
File file = new File(filePath+fileUrl);
String fileName=file.getName();
if (file.exists()) {
// 获得文件的长度
long filesize = file.length();
// 设置输出格式
response.addHeader("content-type", "application/x-msdownload;");
response.addHeader("Content-Disposition", "attachment; filename=" + toUtf8String(fileName));
response.addHeader("content-length", Long.toString(filesize));
// 向客户端写入文件
java.io.FileInputStream fin = new java.io.FileInputStream(file);
byte[] b = new byte[1024];
int j = 0;
while ((j = fin.read(b)) > 0) {
response.getOutputStream().write(b);
}
fin.close();
}else{
response.addHeader("Content-type", "application/x-msdownload;");
response.addHeader("Content-Disposition", "attachment; filename="+ toUtf8String("服务器上已经找不到你要的资源!"));
response.addHeader("content-length", Long.toString(0L));
}
}
/**
* 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
*
* @param s 原文件名
* @return 重新编码后的文件名
*/
private String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) {
k += 256;
}
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}