package com.xquant.xasset.indexapi.business.utils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PoiExport {
@Autowired
private SetDownload setDownload;
/**
* 执行导出
* @param titles 标题字符串,用 , 分割
* @param fileName 导出文件名称
* @param datas 需要导出的数据,{账户标识:[{key:value}{key:value}]}
* @return
*/
public Boolean executeExport(HSSFWorkbook workbook,Map<String,Object>fieldChineseMap, String titles, String fileName, Map<String, List<Map<String, Object>>> datas, HttpServletResponse response) {
Boolean executeResult = true;
// 创建表头
String[] title = titles.split(",");
//创建Excel工作薄
// HSSFWorkbook workbook = new HSSFWorkbook();
Integer sheetNum = 0;
Integer rowNum = 0;//行数
for(Map.Entry<String, List<Map<String, Object>>> map : datas.entrySet()){
rowNum=0;
//创建一个工作表shheet
Sheet sheet = workbook.createSheet(map.getKey());
//创建第一行
Row row = sheet.createRow(rowNum);
Cell cell = null;
HSSFCellStyle style = workbook.createCellStyle(); // 样式对象
Font font = workbook.createFont();
// font.setBoldweight(Font.BOLDWEIGHT_BOLD);// 加粗 //字体增粗
//把字体应用到当前的样式
style.setFont(font);
// 插入第一行
for (int i = rowNum; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(String.valueOf(fieldChineseMap.get(title[i])));
cell.setCellStyle(style);
}
rowNum++;
// 追加数据z
List<Map<String, Object>> data = map.getValue();
Cell cell2 = null;
Integer totalRow = data.size()+rowNum;
for (int i = rowNum; i < totalRow; i++) {// 这里的int 起始是1 也就是第二行开始
Row nexTrow = sheet.createRow(i);
Map rowMap = data.get(i-1);
List<Object> list = parseMap(titles,rowMap);
for(int j=0;j<list.size();j++){
cell2 = nexTrow.createCell(j);
try{
// cell2.setCellValue((String)list.get(j));
HSSFCellStyle contextstyle =workbook.createCellStyle();
Boolean isNum = false;//data是否为数值型
Boolean isInteger=false;//data是否为整数
Boolean isPercent=false;//data是否为百分数
if (list.get(j) != null || "".equals(list.get(j))) {
//判断data是否为数值型
isNum = list.get(j).toString().matches("^(-?\\d+)(\\.\\d+)?$");
//判断data是否为整数(小数部分是否为0)
isInteger=list.get(j).toString().matches("^[-\\+]?[\\d]*$");
//判断data是否为百分数(是否包含“%”)
isPercent=list.get(j).toString().contains("%");
}
//如果单元格内容是数值类型,涉及到金钱(金额、本、利),则设置cell的类型为数值型,设置data的类型为数值类型
if (isNum && !isPercent) {
HSSFDataFormat df = workbook.createDataFormat(); // 此处设置数据格式
if (isInteger) {
contextstyle.setDataFormat(df.getBuiltinFormat("#,#0"));//数据格式只显示整数
}else{
contextstyle.setDataFormat(df.getBuiltinFormat("#,##0.00"));//保留两位小数点
}
// 设置单元格格式
cell2.setCellStyle(contextstyle);
// 设置单元格内容为double类型
cell2.setCellValue(Double.parseDouble(list.get(j).toString()));
} else {
cell2.setCellStyle(contextstyle);
// 设置单元格内容为字符型
if (list.get(j) != null && !"".equals(list.get(j))) {
cell2.setCellValue(String.valueOf(list.get(j)));
} else {
cell2.setCellValue(0);
}
}
}catch (Exception e){
// cell2.setCellValue((Double) list.get(j));
e.printStackTrace();
}
}
}
}
//设置浏览器下载
// setDownload.execute(response, fileName+".xls", workbook);
// 创建一个文件
// File file = new File(exportPath+"\\"+fileName);// 这里可以修改成高版本的
File file = new File(fileName);// 这里可以修改成高版本的
try {
file.createNewFile();
// 将内容存盘
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return executeResult;
}
/**
* 将每一个Map转换成list
* @param title
* @param map
* @return
*/
private List<Object> parseMap(String title, Map map){
List<Object> list = new ArrayList<>();
String[] titleArr = title.split(",");
for(String key : titleArr){
list.add(map.get(key));
}
return list;
}
}
package com.xquant.xasset.indexapi.business.utils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class PoiImageExcelUtils {
public void exportImageToExcel(HSSFWorkbook wb, String imagePath, String sheet, String fileName) {
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;
//先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
try {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(imagePath));
ImageIO.write(bufferImg, "jpg", byteArrayOut);
// HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet(sheet);
//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
//anchor主要用于设置图片的属性
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8);
anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
//插入图片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
fileOut = new FileOutputStream(fileName);
// 写入excel文件
wb.write(fileOut);
System.out.println("----Excle文件已生成------");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fileOut != null){
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.xquant.xasset.indexapi.business.utils;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
public class SetDownload {
/**
* 设置浏览器下载
* @param response 响应
* @param defaultname 导出文件名称 带后缀 .xls .xlsx
* @param workbook 需要导出的工作簿
*/
public void execute(HttpServletResponse response, String defaultname, Workbook workbook){
try{
//下面步骤为浏览器下载部分
//指定数据生成后的文件输入流(将上述out的路径作为文件的输入流)
// FileInputStream fileInputStream = new FileInputStream(tempPath);
//导出excel文件,设置文件名
String filename = URLEncoder.encode(defaultname, "UTF-8");
//设置下载头
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
ServletOutputStream outputStream = response.getOutputStream();
//将文件写入浏览器
// byte[] bys = new byte[fileInputStream.available()];
// fileInputStream.read(bys);
// outputStream.write(bys);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
// fileInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
package com.xquant.xasset.indexapi.business.utils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
public class UploadUtil {
public static File[] resolveCompressUploadFile(HttpServletRequest request,
MultipartFile file, String path) throws Exception {
request.setCharacterEncoding("utf-8");
/* 截取后缀名 */
if (file.isEmpty()) {
throw new Exception("文件不能为空");
}
// String fileName = file.getOriginalFilename();
System.out.println("sssss"+file.getOriginalFilename());
String fileName = new String(file.getOriginalFilename());
System.out.println("fileName"+fileName);
int pos = fileName.lastIndexOf(".");
String extName = fileName.substring(pos + 1).toLowerCase();
// 判断上传文件必须是zip或者是rar否则不允许上传
if (!extName.equals("zip") && !extName.equals("rar")) {
throw new Exception("上传文件格式错误,请重新上传");
}
// 时间加后缀名保存
String saveName = "aaas" + "." + extName;
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
File pushFile = new File(path + "/" + saveName);
File descFile = new File(path);
if (!descFile.exists()) {
descFile.mkdirs();
}
// 解压目的文件
String descDir = path + "/";
System.out.println("desc:" + descDir);
// file.transferTo(pushFile);
FileUtils.copyInputStreamToFile(file.getInputStream(), pushFile);
// 开始解压zip
if (extName.equals("zip")) {
CompressFileUtils.zipToFile(path + "/" + saveName, descDir);
}else if (extName.equals("rar")) {
// 开始解压rar
// CompressFileUtils.unRarFile2(pushFile.getAbsolutePath(), descDir);
} else {
throw new Exception("文件格式不正确不能解压");
}
// 删除 解压完的压缩文件
doDeleteEmptyDir(path + "/" + saveName);
return returnFiles(descDir+"");
}
//返回 File[]
public static File[] returnFiles(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
File f = new File(strPath + File.separator + fileName);
System.out.println("文件名称:"+fileName);
if (f.isDirectory()) {// 如果f是目录
File[] newfiles = f.listFiles();
return newfiles;
}
}
}
return files;
}
//删除指定文件
private static void doDeleteEmptyDir(String dir) {
boolean success = (new File(dir)).delete();
if (success) {
System.out.println("Successfully deleted empty directory: " + dir);
} else {
System.out.println("Failed to delete empty directory: " + dir);
}
}
// 删除目录下的所有
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除目录中的子目录下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//保存file
public static boolean saveFile(File file, String path, String name) throws IOException{
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(path + File.separator
+ name, true);
int count = fis.available();// 获取这个文件里共有多少个字节
byte[] b = new byte[count];
int len = 0;
while ((len = fis.read(b)) != -1) {
fos.write(b);
}
//System.out.println("复制成功!");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
}
package com.xquant.xasset.indexapi.business.utils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Enumeration;
public class CompressFileUtils {
public static void unZipFiles(HttpServletRequest request, String zipPath,
String descDir) throws IOException {
unZipFiles(request, new File(zipPath), descDir);
}
/**
* 解压文件到指定目录
*
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(HttpServletRequest request, File zipFile,
String descDir) throws IOException {
request.setCharacterEncoding("utf-8");
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile);
for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
entry.setUnixMode(644); // 解决linux乱码
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(in);
String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
;
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
// 输出文件路径信息
System.out.println(outPath);
OutputStream out = new FileOutputStream(outPath);
Writer out1 = new OutputStreamWriter(out, "UTF-8");
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
}
/**
* 根据原始rar路径,解压到指定文件夹下.
*
* @param srcRarPath
* 原始rar路径
* @param dstDirectoryPath
* 解压到的文件夹
* @throws UnsupportedEncodingException
*/
// public static void unRarFile(HttpServletRequest request, String srcRarPath,
// String dstDirectoryPath) throws UnsupportedEncodingException {
// request.setCharacterEncoding("utf-8");
// if (!srcRarPath.toLowerCase().endsWith(".rar")) {
// System.out.println("非rar文件!");
// return;
// }
// File dstDiretory = new File(dstDirectoryPath);
// if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
// dstDiretory.mkdirs();
// }
// Archive a = null;
// try {
// a = new Archive(new File(srcRarPath));
// if (a != null) {
// a.getMainHeader().print(); // 打印文件信息.
// FileHeader fh = a.nextFileHeader();
// while (fh != null) {
// String fileName = fh.getFileNameW().isEmpty()?fh.getFileNameString():fh.getFileNameW();
// System.out.println("fileName"+fileName);
// if (fh.isDirectory()) { // 文件夹
// File fol = new File(dstDirectoryPath + File.separator
// + fileName);
// fol.mkdirs();
// } else { // 文件
// File out = new File(dstDirectoryPath + File.separator
// + fh.getFileNameString().trim());
// // System.out.println(out.getAbsolutePath());
// try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
//
// if (!out.exists()) {
// if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
// out.getParentFile().mkdirs();
// }
// out.createNewFile();
// }
// FileOutputStream os = new FileOutputStream(out);
// a.extractFile(fh, os);
// os.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// }
// fh = a.nextFileHeader();
// }
// a.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 解压zip文件
*
* @param sourceFile
* ,待解压的zip文件; toFolder,解压后的存放路径
* @throws Exception
**/
public static void zipToFile(String sourceFile, String toFolder)
throws Exception {
String toDisk = toFolder;// 接收解压后的存放路径
ZipFile zfile = new ZipFile(sourceFile, "GBK");// 连接待解压文件
Enumeration zList = zfile.getEntries();// 得到zip包里的所有元素
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
// log.info("打开zip文件里的文件夹:" + ze.getName() + "skipped...");
continue;
}
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
outputStream = new BufferedOutputStream(new FileOutputStream(
getRealFileName(toDisk, ze.getName())));
inputStream = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, readLen);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
// log.info("解压失败:" + e.toString());
throw new IOException("解压失败:" + e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
inputStream = null;
outputStream = null;
}
}
zfile.close();
}
/**
*
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param zippath
* 指定根目录
*
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
*
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String zippath, String absFileName) {
// log.info("文件名:" + absFileName);
String[] dirs = absFileName.split("/", absFileName.length());
File ret = new File(zippath);// 创建文件对象
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {// 检测文件是否存在
ret.mkdirs();// 创建此抽象路径名指定的目录
}
ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child
// 路径名字符串创建一个新 File 实例
return ret;
}
/**
* 根据原始rar路径,解压到指定文件夹下.
* @param srcRarPath 原始rar路径
* @param dstDirectoryPath 解压到的文件夹
*/
// public static void unRarFile2(String srcRarPath, String dstDirectoryPath) {
// if (!srcRarPath.toLowerCase().endsWith(".rar")) {
// System.out.println("非rar文件!");
// return;
// }
// System.out.println("dstDirectoryPath"+dstDirectoryPath);
// File dstDiretory = new File(dstDirectoryPath);
// if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
// dstDiretory.mkdirs();
// }
// Archive a = null;
// try {
// a = new Archive(new File(srcRarPath));
// if (a != null) {
// //a.getMainHeader().print(); // 打印文件信息.
// FileHeader fh = a.nextFileHeader();
// while (fh != null) {
// //防止文件名中文乱码问题的处理
//
// String fileName = fh.getFileNameW().isEmpty()?fh.getFileNameString():fh.getFileNameW();
// if (fh.isDirectory()) { // 文件夹
// File fol = new File(dstDirectoryPath + File.separator + fileName);
// // fol.mkdirs();
// } else { // 文件
// File out = new File(dstDirectoryPath + File.separator + fileName.trim());
// try {
// if (!out.exists()) {
// if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
// out.getParentFile().mkdirs();
// }
// out.createNewFile();
// }
// FileOutputStream os = new FileOutputStream(out);
// a.extractFile(fh, os);
// os.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// }
// fh = a.nextFileHeader();
// }
// a.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}