javapackage com.lhw.utils;
import com.lhw.common.ResultCodeEnum;
import com.lhw.exception.BusinessException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
/**
* 字符串转换为java.util.Date<br>
* 支持格式为 yyyy.MM.dd G 'at' hh:mm:ss z 如 '2017-12-12 AD at 22:10:59 PSD'<br>
* yy/MM/dd HH:mm:ss 如 '2017/12/12 17:55:00'<br>
* yy/MM/dd HH:mm:ss pm 如 '2017/12/12 17:55:00 pm'<br>
* yy-MM-dd HH:mm:ss 如 '2017-12-12 17:55:00' <br>
* yy-MM-dd HH:mm:ss am 如 '2017-12-12 17:55:00 am' <br>
* @param time String 字符串<br>
* @return Date 日期<br>
*/
public static Date stringToDate(String time){
SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
int len = time.length();
time=time.replace(":","")
.replace("-","")
.replace("/","")
.replace(" ","");
ArrayList<String> formatterList=new ArrayList<>();
formatterList.add("yyyyMMdd");
formatterList.add("yyyyMMddHHmm");
formatterList.add("yyyyMMddHHmm");
formatterList.add("yyyyMMddHHmmss");
for (String strFormatter:formatterList
) {
if(strFormatter.length()==time.length())
formatter=new SimpleDateFormat(strFormatter);
}
return formatter.parse(time);
} catch (Exception e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), e.getMessage());
}
}
public static boolean afterDate(Date d1, Date d2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String strFirstDate = dateFormat.format(d1);
d1 = dateFormat.parse(strFirstDate);
String strSecondDate = dateFormat.format(d2);
d2 = dateFormat.parse(strSecondDate);
} catch (Exception e) {
// 日期型字符串格式错误
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "日期型字符串格式错误。"+e.getMessage());
}
int betweenDays = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
if(c1.after(c2)){
return true;
}else
return false;
}
public static boolean beforeDate(Date d1, Date d2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String strFirstDate = dateFormat.format(d1);
d1 = dateFormat.parse(strFirstDate);
String strSecondDate = dateFormat.format(d2);
d2 = dateFormat.parse(strSecondDate);
} catch (Exception e) {
// 日期型字符串格式错误
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "日期型字符串格式错误。"+e.getMessage());
}
int betweenDays = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
if(c1.before(c2)){
return true;
}
else
return false;
}
public static int getBetweenDays(Date d1, Date d2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String strFirstDate = dateFormat.format(d1);
d1 = dateFormat.parse(strFirstDate);
String strSecondDate = dateFormat.format(d2);
d2 = dateFormat.parse(strSecondDate);
} catch (Exception e) {
// 日期型字符串格式错误
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "日期型字符串格式错误。"+e.getMessage());
}
int betweenDays = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
// 保证第二个时间一定大于第一个时间
if(c1.after(c2)){
c1.setTime(d2);
c2.setTime(d1);
}
int betweenYears = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
betweenDays = c2.get(Calendar.DAY_OF_YEAR)-c1.get(Calendar.DAY_OF_YEAR);
for(int i=0;i<betweenYears;i++){
int tmp=countDays(c1.get(Calendar.YEAR));
betweenDays+=countDays(c1.get(Calendar.YEAR));
c1.set(Calendar.YEAR,(c1.get(Calendar.YEAR)+1));
}
return betweenDays;
}
public static int countDays(int year){
int n=0;
for (int i = 1; i <= 12; i++) {
n += countDays(i,year);
}
return n;
}
public static int countDays(int month, int year){
int count = -1;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
count = 31;
break;
case 4:
case 6:
case 9:
case 11:
count = 30;
break;
case 2:
if(year % 4 == 0)
count = 29;
else
count = 28;
if((year % 100 ==0) & (year % 400 != 0))
count = 28;
}
return count;
}
/**
*
* @Description: 将日期转换为字符串
* @author yehui
* @version 2016年12月27日 下午1:19:15
* @param date
* @param format
* 转化格式,如:yyyy-MM-dd HH:mm:ss
* @return
*
*/
public static String formatDateToString(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String str = sdf.format(date);
return str;
}
public static Date addDays(Date date,int days){
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR,days);
return calendar.getTime();
}
}
java
package com.lhw;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.util.Base64;
import java.util.List;
public class PdfUtils {
public static byte[] MergeFile(List<File> documentPaths) throws IOException, DocumentException {
byte[] mergedDocument;
ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
Document document = new Document();
PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream);
document.open();
for (File docPath : documentPaths) {
PdfReader reader = new PdfReader(docPath.toString());
try {
reader.consolidateNamedDestinations();
int numberOfPages = reader.getNumberOfPages();
for (int page = 0; page < numberOfPages; ) {
PdfImportedPage pdfImportedPage = pdfSmartCopy.getImportedPage(reader, ++page);
pdfSmartCopy.addPage(pdfImportedPage);
}
} finally {
reader.close();
}
}
document.close();
mergedDocument = memoryStream.toByteArray();
return mergedDocument;
}
public static byte[] MergeByteArray(List<ByteArrayOutputStream> byteArrayOutputStreamList) throws IOException, DocumentException {
byte[] mergedDocument;
ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
Document document = new Document();
PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream);
document.open();
for (ByteArrayOutputStream byteArrayOutputStream : byteArrayOutputStreamList) {
PdfReader reader = new PdfReader(byteArrayOutputStream.toByteArray());
try {
reader.consolidateNamedDestinations();
int numberOfPages = reader.getNumberOfPages();
for (int page = 0; page < numberOfPages; ) {
PdfImportedPage pdfImportedPage = pdfSmartCopy.getImportedPage(reader, ++page);
pdfSmartCopy.addPage(pdfImportedPage);
}
} finally {
reader.close();
}
}
document.close();
mergedDocument = memoryStream.toByteArray();
return mergedDocument;
}
/**
* @param destPath 生成pdf文件的路劲
* @param images 需要转换的图片路径的数组
* @throws IOException
* @throws DocumentException
*/
public static void imagesToPdf(String destPath, String[] images)
throws IOException, DocumentException {
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(destPath));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
int len = images.length;
for (int i = 0; i < len; i++) {
Image img = Image.getInstance(images[i]);
img.setAlignment(Image.ALIGN_CENTER);
//根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
}
// 第五步:关闭文档。
document.close();
}
/**
* @param destPath 生成pdf文件的路劲
*
* @throws IOException
* @throws DocumentException
*/
public static void imagesToPdf(String destPath, String base64Image)
throws IOException, DocumentException {
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(destPath));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
Image img= FileUtils.base64ToImage(base64Image);
img.setAlignment(Image.ALIGN_CENTER);
//根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
// 第五步:关闭文档。
document.close();
}
/**
*
* @Description: 此方法的作用是将pdf文件流加上文字水印再返回文件流
* @Param: @param null
* @author lihaowei
* @since: 2023/11/7 17:12
* @return byte[]
*/
public static byte[] PDFAddWatermark(byte[] pdfbyte, String waterMarkName) throws Exception {
// 每页水印行数
int row = 7;
// 每行水印个数
int col = 3;
// 旋转角度
float rotation = 30f;
// 读取PDF
PdfReader reader = new PdfReader(pdfbyte);
//创建字节数组输出流
ByteArrayOutputStream ous =new ByteArrayOutputStream();
// 创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(ous);
// 输出的PDF文件内容
PdfStamper stamper = new PdfStamper(reader, bos);
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.2f);//改透明度
gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
PdfContentByte content;
int total = reader.getNumberOfPages();//pdf文件页数
for (int i=0; i<total; i++) {
// 在内容上方加水印
content = stamper.getOverContent(i+1);
// 在内容下方加水印
// content = stamper.getUnderContent(i+1);
//开始写入
content.beginText();
content.setGState(gs);
//字体大小
content.setFontAndSize(base, 20);
//每页7行,一行3个
for (int j=0; j<col; j++) {
for (int k=0; k<row; k++) {
float x = reader.getPageSize(i+1).getWidth() / col * j + 90;
float y = reader.getPageSize(i+1).getHeight() / row * k;
//showTextAligned 方法的参数(文字对齐方式,位置内容,输出水印X轴位置,Y轴位置,旋转角度)
content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, rotation);
}
}
// 添加水印文字
content.endText();
}
stamper.close();
//添加水印后pdf的base64
byte[] bytes = ous.toByteArray();
ous.close();
bos.close();
reader.close();
return bytes;
}
/**
* 将图片的base64转成pdf的输入流
* @param imageBase64
* @return
*/
public static InputStream imageToPdfInputSteam(String imageBase64){
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 第二步:
// 创建一个PdfWriter实例,
try {
PdfWriter.getInstance(document, os);
} catch (DocumentException e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "转换失败文档异常");
}
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
Image img= FileUtils.base64ToImage(imageBase64);
img.setAlignment(Image.ALIGN_CENTER);
//根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
try {
document.add(img);
} catch (DocumentException e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(),"添加document对象失败");
}
// 第五步:关闭文档。
document.close();
return new ByteArrayInputStream(os.toByteArray());
}
/**
* 将图片的BaseBase64编码转换成PDF的Base64编码
* @param imageBase64
* @return
*/
public static String imageToPdfBase64(String imageBase64) {
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 第二步:
// 创建一个PdfWriter实例,
try {
PdfWriter.getInstance(document, os);
} catch (DocumentException e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "转换失败文档异常");
}
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
Image img = FileUtils.base64ToImage(imageBase64);
img.setAlignment(Image.ALIGN_CENTER);
//根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
try {
document.add(img);
} catch (DocumentException e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1000.getCode(), "添加document对象失败");
}
// 第五步:关闭文档。
return Base64.getEncoder().encodeToString(os.toByteArray());
}
}
java
package com.lhw.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
public static String generateId(){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(new Date());
UUID uuid = UUID.randomUUID();
return date+uuid.toString();
}
public static String SqlFormat(String sql, Map<String,Object> htEnvVar){
String regex="(?<=\\#)\\S+(?=\\#)";
Pattern pat=Pattern.compile(regex);
Matcher mat=pat.matcher(sql);
int i=0;
while(mat.find()){
i++;
String str1="#"+mat.group(0)+"#";
if(htEnvVar.containsKey(mat.group(0)))
{
String str2=(String) htEnvVar.get(mat.group(0));
sql=sql.replaceAll(str1,str2);
}
}
return sql;
}
}
java
package com.lhw.utils;
import cn.hutool.Hutool;
import cn.hutool.core.codec.Base64Decoder;
import com.google.common.base.Preconditions;
import com.itextpdf.text.Image;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class FileUtils {
public static FileItem createFileItem(File file, String fieldName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
public static String encryptToBase64(String filePath){
if(filePath==null)
return null;
try{
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
}catch (IOException e){
e.printStackTrace();
return null;
}
}
public static InputStream base64ToInputStream(String base64Str){
ByteArrayInputStream stream=null;
try{
Base64Decoder decoder=new Base64Decoder();
byte[] bytes= Base64.getDecoder().decode(base64Str);
stream=new ByteArrayInputStream(bytes);
}catch (Exception e){
e.printStackTrace();
}
finally {
return stream;
}
}
public static Image base64ToImage(String base64Str){
ByteArrayInputStream stream=null;
Image image =null;
try{
Base64Decoder decoder=new Base64Decoder();
byte[] bytes= Base64.getDecoder().decode(base64Str);
stream=new ByteArrayInputStream(bytes);
int n;
byte[] buffer = new byte[4096];
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (-1 != (n = stream.read(buffer))) {
output.write(buffer, 0, n);
}
image = Image.getInstance(output.toByteArray());
}catch (Exception e){
e.printStackTrace();
}
finally {
return image;
}
}
public static void base64ToFile(String targetFile,String base64 ) {
File file = null;
File dir=new File("d:\\");
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.getDecoder().decode(base64);
file=new File(targetFile);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static final String CLASSPATH_FILE_FLAG = "classpath:";
public static String getAbsoluteFilePath(String fileName) throws IOException {
Preconditions.checkArgument(StringUtils.isNotBlank(fileName), "file name can't be null or empty");
if (absolutePathStart(fileName)) {
Preconditions.checkArgument(isFileExist(fileName), fileName + " dose not exist");
return fileName;
} else if (fileName.startsWith(CLASSPATH_FILE_FLAG)) {
fileName = fileName.substring(CLASSPATH_FILE_FLAG.length()).trim();
Preconditions.checkArgument(StringUtils.isNotBlank(fileName), "file name can't be null or empty");
URL base = getClassLoader().getResource("");
return new File(base.getFile(), fileName).getCanonicalPath();
} else {
String userDir = System.getProperty("user.dir");
return new File(addSeparator(userDir) + fileName).getCanonicalPath();
}
}
public static String addSeparator(String dir) {
if (!dir.endsWith(File.separator)) {
dir += File.separator;
}
return dir;
}
private static ClassLoader getClassLoader() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = FileUtils.class.getClassLoader();
}
return classLoader;
}
private static boolean absolutePathStart(String path) {
File[] files = File.listRoots();
for (File file : files) {
if (path.startsWith(file.getPath())) {
return true;
}
}
return false;
}
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}
}
java
package com.lhw.utils;
import com.lhw.common.ResultCodeEnum;
import com.lhw.exception.BusinessException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* Created by zuifengke on 2017/8/8.
*/
public class FtpUtil {
private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
private String url;
private String port;
private String username;
private String password;
private String dir;
private String config = "";
private static String OS = System.getProperty("os.name").toLowerCase();
private FTPClient ftpClient;
public String getUrl() {
return url;
}
public String getPort() {
return port;
}
public FtpUtil() {
ftpClient = new FTPClient();
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setDefaultTimeout(300000);
ftpClient.setConnectTimeout(300000);
ftpClient.setDataTimeout(300000);
ftpClient.configure(getClientConfig());
}
public void getConn(String ftpConfig) {
if (config.equals(ftpConfig)) {
return;
}
System.out.println("reading FTP Config...");
try {
if (ftpConfig.indexOf("/", ftpConfig.indexOf("@")) == -1) {
dir = "";
port = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("@")) + 1);
} else {
dir = ftpConfig.substring(ftpConfig.indexOf("/", ftpConfig.indexOf("@")) + 1);
port = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("@")) + 1, ftpConfig.indexOf("/", ftpConfig.indexOf("@")));
}
url = ftpConfig.substring(ftpConfig.indexOf("@") + 1, ftpConfig.indexOf(":", ftpConfig.indexOf("@") - 1));
username = ftpConfig.substring(ftpConfig.indexOf("//") + 2, ftpConfig.indexOf(":", ftpConfig.indexOf("//")));
password = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("//")) + 1, ftpConfig.indexOf("@"));
} catch (Exception e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(), "FTP系统参数配置出错");
}
if ("".equals(dir)) {
config = "ftp://" + username + ":" + password + "@" + url + ":" + port;
} else {
config = "ftp://" + username + ":" + password + "@" + url + ":" + port + "/" + dir;
}
System.out.println(config);
}
private void ftpConnect(String url, String port, String username, String password) {
System.out.println("连接" + config);
try {
ftpClient.connect(url, Integer.parseInt(port));
boolean loginResult = ftpClient.login(username, password);
int returnCode = ftpClient.getReplyCode();
if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {
System.out.println("ftp连接成功");
} else {
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP连接失败");
}
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP客户端出错或已关闭!"+ e.toString());
}
}
public void ftpDisconnect() {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
System.out.println("关闭ftp连接");
}
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"关闭FTP连接发生异常!");
}
}
public boolean fileExist(String remotePath, String fileName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
//新方法
boolean b = ftpClient.changeWorkingDirectory(remotePath);
ftpClient.enterLocalPassiveMode(); // Use passive mode as default
String[] nameList = ftpClient.listNames();
for (String s : nameList) {
if (s.equals(fileName)) {
return true;
}
}
logger.info("读取文件信息不存在:"+remotePath +"/"+fileName);
return false;
} catch (NullPointerException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"文件不存在!" );
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP文件读取发生异常!");
} finally {
ftpDisconnect();
}
}
public boolean fileUpload(String remotePath, String fileName, InputStream fis) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
System.out.println("上传'" + fileName + "'到" + remotePath);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.makeDirectory(dir + remotePath);
ftpClient.changeWorkingDirectory(dir + remotePath);
ftpClient.enterLocalPassiveMode();
System.out.println("uploading...");
boolean returnMessage = ftpClient.storeFile(fileName, fis);
if (returnMessage) {
System.out.println("上传成功...");
}
return returnMessage;
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP文件上传发生异常!");
} finally {
IOUtils.closeQuietly(fis);
}
}
public boolean fileRename(String path, String oldName, String newName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
System.out.println("文件重命名");
ftpClient.changeWorkingDirectory(dir + path);
ftpClient.enterLocalPassiveMode();
return ftpClient.rename(oldName, newName);
} catch (IOException e) {
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP文件重命名发生异常!");
}
}
public boolean fileDelete(String pathName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
System.out.println("删除" + pathName);
ftpClient.enterLocalPassiveMode();
boolean returnMessage = ftpClient.deleteFile(dir + pathName);
if (returnMessage) {
System.out.println("删除成功!");
}
return returnMessage;
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP文件删除发生异常!");
}
}
public ByteArrayOutputStream fileGet(String path, String fileName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(dir + path);
ftpClient.enterLocalPassiveMode();
System.out.println("读取文件信息:" + path + "/" + fileName);
InputStream ins = ftpClient.retrieveFileStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = ins.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
ins.close();
System.out.println("文件读取完成");
return baos;
} catch (NullPointerException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"文件不存在!");
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1002.getCode(),"FTP文件读取发生异常!");
} finally {
ftpDisconnect();
}
}
public ByteArrayOutputStream fileExistAndGet(String remotePath, String fileName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.enterLocalPassiveMode(); // Use passive mode as default
String[] nameList = ftpClient.listNames();
for (String s : nameList) {
if (s.equals(fileName)) {
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(dir + remotePath);
ftpClient.enterLocalPassiveMode();
System.out.println("读取文件信息:" + remotePath + "/" + fileName);
InputStream ins = ftpClient.retrieveFileStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = ins.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
ins.close();
System.out.println("文件读取完成");
return baos;
}
}
logger.info("读取文件信息不存在:"+remotePath +"/"+fileName);
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"文件不存在!" );
} catch (NullPointerException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"文件不存在!" );
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"FTP文件读取发生异常!");
} finally {
ftpDisconnect();
}
}
public ByteArrayOutputStream fileExistAndGet(String remotePath, String fileName) {
if (!ftpClient.isConnected()) {
ftpConnect(url, port, username, password);
}
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.enterLocalPassiveMode(); // Use passive mode as default
String[] nameList = ftpClient.listNames();
for (String s : nameList) {
if (s.equals(fileName)) {
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(dir + remotePath);
ftpClient.enterLocalPassiveMode();
System.out.println("读取文件信息:" + remotePath + "/" + fileName);
InputStream ins = ftpClient.retrieveFileStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = ins.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
ins.close();
System.out.println("文件读取完成");
return baos;
}
}
logger.info("读取文件信息不存在:"+remotePath +"/"+fileName);
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"文件不存在!" );
} catch (NullPointerException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"文件不存在!" );
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(ResultCodeEnum.ERR_0x1004.getCode(),"FTP文件读取发生异常!");
} finally {
ftpDisconnect();
}
}
private static FTPClientConfig getClientConfig() {
String sysType = null;
if (isLinux()) {
sysType = FTPClientConfig.SYST_UNIX;
} else if (isWindows()) {
sysType = FTPClientConfig.SYST_NT;
}
FTPClientConfig config = new FTPClientConfig(sysType);
config.setRecentDateFormatStr("yyyy-MM-dd HH:mm");
return config;
}
private static boolean isLinux() {
return OS.contains("linux");
}
private static boolean isWindows() {
return OS.contains("windows");
}
public static String convertStreamToString(InputStream is, String encoding) {
ByteArrayOutputStream bao = null;
String result = "";
try {
bao = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
bao.write(buf, 0, len);
}
result = new String(bao.toByteArray(), encoding);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String getMedDocPath(String patientId, String visitId) {
if (patientId.length() <= 10) {
patientId = StringUtils.rightPad(patientId, 9, "0") + patientId.length();
} else {
patientId = StringUtils.leftPad(patientId, 10, "0");
}
StringBuilder newPatientId = new StringBuilder();
try {
byte[] bytes = patientId.getBytes(StandardCharsets.US_ASCII);
for (byte bt : bytes) {
String ascii = "";
int asciiLength = (int) bt % 10;
ascii = Integer.toString(asciiLength);
newPatientId.append(ascii);
}
patientId = newPatientId.toString();
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder ftpPath = new StringBuilder("/MEDDOC");
for (int i = 0; i < 10; i += 2) {
ftpPath.append("/");
ftpPath.append(patientId, i, i + 2);
}
ftpPath.append("/").append("IP").append("_").append(visitId);
return ftpPath.toString();
}
}
java
package com.lhw.utils;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
* 描述:Redis工具类
* @author hanjia
* @date 2021/8/2 14:17
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
//=============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间
* @param timeUnit 时间单位
* @return true/false
*/
public boolean expire(String key, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
redisTemplate.expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key, TimeUnit timeUnit) {
return redisTemplate.getExpire(key, timeUnit);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
public void del(String ... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(Arrays.asList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public <T> T get(String key, Class<T> clazz) {
Object obj = redisTemplate.opsForValue().get(key);
try {
return parseObject(obj, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @return 数字
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @return 数字
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time, TimeUnit timeUnit) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time, TimeUnit timeUnit) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
//============================set=============================
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
Set<Object> members = redisTemplate.opsForSet().members(key);
return members;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(TimeUnit timeUnit,String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0){
expire(key, time,timeUnit);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public <T> List<T> lGet(String key, long start, long end, Class<T> clazz) {
List<Object> objects = lGet(key, start, end);
List<T> list = new ArrayList<>();
if (CollectionUtils.isEmpty(objects)) {
return list;
}
for (Object object : objects) {
List<T> list1 = parseArray(object, clazz);
if (!CollectionUtils.isEmpty(list1)) {
list.addAll(list1);
}
}
return list;
}
/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public <T> T lGetIndex(String key, long index, Class<T> clazz) {
Object obj = lGetIndex(key, index);
return parseObject(obj,clazz);
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time,TimeUnit timeUnit) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0){
expire(key, time,timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time,TimeUnit timeUnit) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0){
expire(key, time,timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将redis取出来的object转为指定的对象
* @param object redis取出来的对象
* @param clazz 转换为指定的对象
* @return T
**/
private <T> T parseObject(Object object,Class<T> clazz) {
if (Objects.isNull(object)) {
return null;
}
return JSON.parseObject(JSON.toJSONString(object),clazz);
}
/**
* 将redis取出来的object转为指定的对象
* @param object redis取出来的对象
* @param clazz 转换为指定的对象
* @return T
**/
private <T> List<T> parseArray(Object object,Class<T> clazz) {
if (Objects.isNull(object)) {
return null;
}
return JSON.parseArray(JSON.toJSONString(object),clazz);
}
/**
* 删除缓存
* @param key 键
*/
public void delKey(String key) {
redisTemplate.delete(key);
}
/**
* 获取缓存List
* @param key 键
* @param clazz 映射类型
* @return 缓存列表
*/
public <T> List<T> getList(String key, Class<T> clazz) {
List<Object> redisList = redisTemplate.opsForList().range(key, 0, -1);
List<T> list = Lists.newArrayList();
if (CollectionUtils.isEmpty(redisList)) {
return list;
}
ObjectMapper mapper = new ObjectMapper();
redisList.forEach(e -> list.add(mapper.convertValue(e, clazz)));
return list;
}
/**
* 添加缓存,类型为List
* @param key 键
* @param list 数据列表
* @param <T> 泛型
*/
public <T> void rightPushAll(String key, List<T> list) {
redisTemplate.opsForList().rightPushAll(key, list.toArray());
}
}
java
package com.lhw.utils;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
/**
*
* 压缩文件工具类
*/
public class ZipUtil {
private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);
/**
*
* 压缩指定路径的文件
* @param srcFilePath 待压缩文件路径
* @param zipPathFileName zip文件全路径名
* @param password 加密密码
* @return
*/
public static boolean zipFile(String srcFilePath, String zipPathFileName, String password){
try {
// 生成的压缩文件
ZipFile zipFile = new ZipFile(zipPathFileName);
ZipParameters parameters = new ZipParameters();
// 压缩级别
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(!StringUtils.isEmpty(password)){
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
// 要打包的文件夹
File currentFile = new File(srcFilePath);
File[] fs = currentFile.listFiles();
// 遍历test文件夹下所有的文件、文件夹
for (File f : fs) {
if (f.isDirectory()) {
zipFile.addFolder(f.getPath(), parameters);
} else {
zipFile.addFile(f, parameters);
}
}
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("压缩文件【"+srcFilePath+"】到路径【"+zipPathFileName+"】失败:\n"+e.getMessage());
return false;
}
}
/**
* @param zipFileFullName zip文件所在的路径名
* @param password 需要解压的密码
* @return
*/
public static HashSet<String> unZipFile(String zipFileFullName, String password) {
HashSet<String> filePathSet = new HashSet<>();
// 获取当前文件夹下的所有已经解压的文件
File newFile = new File(zipFileFullName);
String[] newList = newFile.list();
Map<String, String> zippedMap = new HashMap<>();
for (String file_name : newList) {
if(!file_name.contains(".zip")){
String key = zipFileFullName + File.separator +file_name+".zip";
zippedMap.put(key,file_name);
}
}
try {
List<String> fileNames = new ArrayList<>();
findFileList(new File(zipFileFullName),fileNames);
for (String fileName : fileNames) {
ZipFile zipFile = new ZipFile(fileName);
if(zippedMap.containsKey(fileName)){
continue;
}
// 如果解压需要密码
if(StringUtils.isNotEmpty(password)&&zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
String[] split = {};
if(File.separator.equals("/")){
split = fileName.split("/");
}
if(File.separator.equals("\\")){
split = fileName.split("\\\\");
}
String filePathName = split[split.length-1];
String filePath = filePathName.replace(".zip","");
String newPath = zipFileFullName + File.separator + filePath;
filePathSet.add(newPath);
zipFile.extractAll(newPath);
}
return filePathSet;
} catch (ZipException e) {
e.printStackTrace();
return filePathSet;
}
}
/**
* 读取目录下的所有文件
*
* @param dir
* 目录
* @param fileNames
* 保存文件名的集合
* @return
*/
public static void findFileList(File dir, List<String> fileNames) {
if (!dir.exists() || !dir.isDirectory()) {// 判断是否存在目录
return;
}
String[] files = dir.list();// 读取目录下的所有目录文件信息
for (int i = 0; i < files.length; i++) {// 循环,添加文件名或回调自身
File file = new File(dir, files[i]);
if (file.isFile()) {// 如果文件
String name = file.getName();
if(name.startsWith("password-backup")) {
fileNames.add(dir + File.separator + file.getName());// 添加文件全路径名
}
if(name.startsWith("sc-done")){
fileNames.add(dir + File.separator + file.getName());// 添加文件全路径名
}
} else {// 如果是目录
findFileList(file, fileNames);// 回调自身继续查询
}
}
}
/**
* 添加文件到压缩文件中
* @param zipFullFileName zip文件所在路径及全名
* @param fullFileNameList 待添加的文件全路径集合
* @param rootFolderInZip 在压缩文件里的文件夹名
* @return
*/
public static boolean addFilesToZip(String zipFullFileName, List<String> fullFileNameList, String rootFolderInZip) {
try {
ZipFile zipFile = new ZipFile(zipFullFileName);
ArrayList<File> addFiles = new ArrayList<>();
for (String fileName:fullFileNameList) {
addFiles.add(new File(fileName));
}
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(StringUtils.isNotEmpty(rootFolderInZip)){
if(rootFolderInZip.endsWith("/")==false){
rootFolderInZip = rootFolderInZip+"/";
}
parameters.setRootFolderInZip(rootFolderInZip);
}
zipFile.addFiles(addFiles, parameters);
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("添加文件失败:\n"+e.getMessage());
return false;
}
}
/**
* 从压缩文件中删除路径
* @param zipFullFileName
* @param fileName
* @return
*/
public static boolean deleteFileInZip(String zipFullFileName, String fileName) {
try {
ZipFile zipFile = new ZipFile(zipFullFileName);
zipFile.removeFile(fileName);
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("删除文件失败:\n"+e.getMessage());
return false;
}
}
public static void encrypt_zip(String src_file, String dst_file, String encode) {
File file = new File(src_file);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);//压缩方式
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);//加密方式
parameters.setPassword(encode.toCharArray());//设置密码
try {
ZipFile zipFile = new ZipFile(dst_file);
zipFile.setFileNameCharset("gbk");
zipFile.addFile(file, parameters);
} catch (net.lingala.zip4j.exception.ZipException e) {
e.printStackTrace();
}
}
/**
* @param source
* 原始文件路径
* @param dest
* 解压路径
* @param password
* 解压文件密码(可以为空)
*/
public static void unZip(String source, String dest, String password) {
try {
File zipFile = new File(source);
// 首先创建ZipFile指向磁盘上的.zip文件
ZipFile zFile = new ZipFile(zipFile);
zFile.setFileNameCharset("GBK");
File destDir = new File(dest);
if (!destDir.exists()) {
destDir.mkdirs();
}
if (zFile.isEncrypted()) {
// 设置密码
zFile.setPassword(password.toCharArray());
}
// 将文件抽出到解压目录(解压)
zFile.extractAll(dest);
List<FileHeader> headerList = zFile.getFileHeaders();
List<File> extractedFileList = new ArrayList<File>();
for (FileHeader fileHeader : headerList) {
if (!fileHeader.isDirectory()) {
extractedFileList.add(new File(destDir, fileHeader.getFileName()));
}
}
File[] extractedFiles = new File[extractedFileList.size()];
extractedFileList.toArray(extractedFiles);
for (File f : extractedFileList) {
System.out.println(f.getAbsolutePath() + "文件解压成功!");
}
} catch (ZipException e) {
e.printStackTrace();
}
}
}
java
package com.lhw.utils;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.params.ExcelForEachParams;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;
/*
* @Author lihaowei
* @Description: //TODO
* @Date 11:46 2022/7/14
* @Param
* @return
*/
public class ExcelStylesUtil implements IExcelExportStyler {
private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");
private static final short FONT_SIZE_TEN = 10;
private static final short FONT_SIZE_NINE = 9;
/**
* 大标题样式
*/
private CellStyle headerStyle;
/**
* 每列标题样式
*/
private CellStyle titleStyle;
/**
* 数据行样式
*/
private CellStyle styles;
public ExcelStylesUtil(Workbook workbook) {
this.init(workbook);
}
/**
* 初始化样式
*
* @param workbook
*/
private void init(Workbook workbook) {
this.headerStyle = initHeaderStyle(workbook);
this.titleStyle = initTitleStyle(workbook);
this.styles = initStyles(workbook);
}
/**
* 大标题样式
*
* @param color
* @return
*/
@Override
public CellStyle getHeaderStyle(short color) {
return headerStyle;
}
/**
* 每列标题样式
*
* @param color
* @return
*/
@Override
public CellStyle getTitleStyle(short color) {
return titleStyle;
}
/**
* 数据行样式
*
* @param parity 可以用来表示奇偶行
* @param entity 数据内容
* @return 样式
*/
@Override
public CellStyle getStyles(boolean parity, ExcelExportEntity entity) {
return styles;
}
/**
* 获取样式方法
*
* @param dataRow 数据行
* @param obj 对象
* @param data 数据
*/
@Override
public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {
return getStyles(true, entity);
}
/**
* 模板使用的样式设置
*/
@Override
public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {
return null;
}
/**
* 初始化--大标题样式
*
* @param workbook
* @return
*/
private CellStyle initHeaderStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_TEN, true));
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
}
/**
* 初始化--每列标题样式
*
* @param workbook
* @return
*/
private CellStyle initTitleStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_NINE, true));
//背景色
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
}
/**
* 初始化--数据行样式
*
* @param workbook
* @return
*/
private CellStyle initStyles(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_NINE, false));
style.setDataFormat(STRING_FORMAT);
return style;
}
/**
* 基础样式
*
* @return
*/
private CellStyle getBaseCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
//下边框
style.setBorderBottom(BorderStyle.THIN);
//左边框
style.setBorderLeft(BorderStyle.THIN);
//上边框
style.setBorderTop(BorderStyle.THIN);
//右边框
style.setBorderRight(BorderStyle.THIN);
//水平居中
style.setAlignment(HorizontalAlignment.CENTER);
//上下居中
style.setVerticalAlignment(VerticalAlignment.CENTER);
//设置自动换行
style.setWrapText(true);
return style;
}
/**
* 字体样式
*
* @param size 字体大小
* @param isBold 是否加粗
* @return
*/
private Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
//字体样式
font.setFontName("宋体");
//是否加粗
font.setBold(isBold);
//字体大小
font.setFontHeightInPoints(size);
return font;
}
}
java
package com.lhw.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
//import com.ewell.medqc.rec.enums.N420DfbEnum;
//import com.linuxense.javadbf.DBFDataType;
//import com.linuxense.javadbf.DBFField;
//import com.linuxense.javadbf.DBFWriter;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
//import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
//import static org.apache.tika.utils.CharsetUtils.forName;
public class ExportUtils {
/**
* 基于poi的方式导出dbf文件
* @param fileName 文件名
* @param response HttpServletResponse
* @param dataList 需要导出的行数据
* @param headList 需要导出的列数据
* @throws Exception
*/
public static void exportPoiToDbf(String fileName, List<List<String>> headList ,List<List<Object>> dataList, HttpServletResponse response) throws IOException {
try (Workbook workbook = new XSSFWorkbook(); OutputStream out = response.getOutputStream()) {
Sheet sheet = workbook.createSheet();
Row rowHeader = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
List<String> head = headList.get(i);
Cell cell = rowHeader.createCell(i, CellType.STRING);
String headerName = StringUtils.defaultString(head.get(0));
cell.setCellValue(headerName);
}
if (CollectionUtil.isNotEmpty(dataList)) {
for (int i = 0; i < dataList.size(); i++) {
List<Object> data = dataList.get(i);
Row rowData = sheet.createRow(i + 1);
for (int j = 0; j < data.size(); j++) {
Cell cell = rowData.createCell(j);
String value = data.get(j) != null ? data.get(j).toString() : "";
cell.setCellValue(value);
}
}
}
response.setContentType("application/x-dbf");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".dbf", "utf-8"));
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
// 重置response
outputErrorJson(response,e.getMessage());
}
}
/**
* 基于xml的方式导出dbf文件
* @param fileName 导出的文件名
* @param response HttpServletResponse
* @param dataList 需要导出的行数据
* @param headList 需要导出的列数据
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" }) //忽略警告
public static void exportXmlToDbf(String fileName,List<List<String>> headList,List<List<Object>> dataList, HttpServletResponse response) throws IOException {
// 创建一个excel应用文件
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("\n");
sb.append("<?mso-application progid=\"Excel.Sheet\"?>");
sb.append("\n");
sb.append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
sb.append("\n");
sb.append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
sb.append("\n");
sb.append(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
sb.append("\n");
sb.append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
sb.append("\n");
sb.append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
sb.append("\n");
sb.append("<Styles>\n");
/*设置列头样式*/
sb.append("<Style ss:ID=\"header\" ss:Name=\"header\">\n");//ss:ID=“header”对应下面的Row ss:StyleID=“header”
sb.append("<Font ss:FontName=\"Arial\" x:CharSet=\"134\" ss:Bold=\"Bolder\" ss:Size=\"10\"/>\n");//设置字体
sb.append("</Style>\n");
/*其它默认样式设置*/
sb.append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n");
sb.append("<Alignment ss:Vertical=\"Center\"/>\n");
sb.append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"10\"/>\n");
sb.append("<Interior/>\n");
sb.append("<NumberFormat/>\n");
sb.append("<Protection/>\n");
sb.append("</Style>\n");
sb.append("</Styles>\n");
try {
// 生成表格
int headersLength = headList.size();
sb.append("<Worksheet ss:Name=\"" + "Sheet1" + "\">");
sb.append("\n");
sb.append("<Table ss:ExpandedColumnCount=\"" + headersLength
+ "\" ss:ExpandedRowCount=\"1000000\" x:FullColumns=\"1\" x:FullRows=\"1\">");
sb.append("\n");
// 输出列头
sb.append("<Row>");
for (int i = 0; i < headersLength; i++) {
sb.append("<Cell ss:StyleID=\"header\"><Data ss:Type=\"String\">" + headList.get(i).get(0) + "</Data></Cell>");
}
sb.append("</Row>");
// 构建表体数据
for (int j = 0; j < dataList.size(); j++) {
sb.append("<Row>");
for (int i = 0; i < dataList.get(0).size(); i++) {
sb.append("<Cell><Data ss:Type=\"String\">");
sb.append(String.valueOf(dataList.get(j).get(i)).equals("null")?"":String.valueOf(dataList.get(j).get(i)));
sb.append("</Data></Cell>");
}
sb.append("</Row>");
sb.append("\n");
}
sb.append("</Table>");
sb.append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
sb.append("\n");
sb.append("<ProtectObjects>False</ProtectObjects>");
sb.append("\n");
sb.append("<ProtectScenarios>False</ProtectScenarios>");
sb.append("\n");
sb.append("</WorksheetOptions>");
sb.append("\n");
sb.append("</Worksheet>");
sb.append("</Workbook>");
sb.append("\n");
response.setContentType("application/x-dbf;charset=UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".dbf", "utf-8"));
response.getOutputStream().write(sb.toString().getBytes());
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
outputErrorJson(response,e.getMessage());
}
}
/**
* 基于easyExcel的方式导出dbf文件
* @param fileName 导出的文件名
* @param response HttpServletResponse
* @param dataList 需要导出的行数据
* @param headList 需要导出的列数据
* @throws Exception
*/
public static void exportEasyExcelToDbf(String fileName,List<List<String>> headList,List<List<Object>> dataList,HttpServletResponse response) throws IOException {
//导出dbf的话需要将date里的类型转成String类型才能满足上报要求
List<List<String>> strdataList =dataList.stream().map(innerList -> innerList.stream().map(m->m==null? "": String.valueOf(m)).collect(Collectors.toList())).collect(Collectors.toList());
try {
response.setContentType("application/x-dbf;charset=UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".dbf", "utf-8"));
//设置列名的字体大小
WriteFont headWriteFont = new WriteFont();
//设置字体大小为10
headWriteFont.setFontHeightInPoints((short) 10);
//取消加粗
headWriteFont.setBold(false);
//设置字体为Arial
headWriteFont.setFontName("Arial");
//列名单元的风格对象
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setWriteFont(headWriteFont);
//设置前景色为白色
// headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//去除列名边框
headWriteCellStyle.setBorderTop(BorderStyle.NONE);
headWriteCellStyle.setBorderLeft(BorderStyle.NONE);
headWriteCellStyle.setBorderRight(BorderStyle.NONE);
headWriteCellStyle.setBorderBottom(BorderStyle.NONE);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy();
horizontalCellStyleStrategy.setHeadWriteCellStyle(headWriteCellStyle);
WriteCellStyle cellStyle=new WriteCellStyle();
WriteFont cellWriteFont = new WriteFont();
cellWriteFont.setFontHeightInPoints((short) 10);
cellWriteFont.setFontName("宋体");
cellStyle.setWriteFont(cellWriteFont);
List<WriteCellStyle> writeCellStyleList = new ArrayList<>();
writeCellStyleList.add(cellStyle);
horizontalCellStyleStrategy.setContentWriteCellStyleList(writeCellStyleList);
EasyExcel.write(response.getOutputStream()).registerWriteHandler(horizontalCellStyleStrategy).head(headList).autoCloseStream(Boolean.FALSE).sheet("sheet").doWrite(strdataList);
} catch (IOException e) {
e.printStackTrace();
// 重置response
outputErrorJson(response,e.getMessage());
}
}
/**
* 基于javadbf的方式导出dbf文件
* @param response HttpServletResponse
* @param dataList 需要导出的行数据
* @param headList 需要导出的列数据
* @throws Exception
*/
// public static void exportJavaDbfToDbf(String fileName,List<List<String>> headList,List<List<Object>> dataList,HttpServletResponse response) throws IOException {
// try (OutputStream fos = response.getOutputStream()) {
// response.setContentType("application/x-dbf");
// response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".dbf", "utf-8"));
// //先需要设置一下表结构--列名
// DBFField[] dbfFields = new DBFField[headList.size()];
// Map<Integer,String> noStrMap= new HashMap<>();
// for (int i = 0; i < headList.size(); i++) {
// dbfFields[i] = new DBFField();
// dbfFields[i].setName(headList.get(i).get(0));
// // dbf表 字符类型 的字段长度最大不能超过254
// if (N420DfbEnum.getColumnType(headList.get(i).get(0))!=null){
// dbfFields[i].setType(DBFDataType.NUMERIC);
// dbfFields[i].setLength(5);
// noStrMap.put(i,"F");
// }else {
// dbfFields[i].setType(DBFDataType.CHARACTER);
// dbfFields[i].setLength(30);
// }
// }
// Charset defaultCharset = forName("GBK");
// DBFWriter writer = new DBFWriter(fos, defaultCharset);
// writer.setFields(dbfFields);
// //然后一条一条的往里面插数据
// for (int i = 0; i < dataList.size(); i++) {
// Object[] rowData = new Object[dataList.get(0).size()];
// for (int j = 0; j < dataList.get(0).size(); j++) {
// if (!noStrMap.containsKey(j)){
// rowData[j]=String.valueOf(dataList.get(i).get(j)).equals("null")?"":String.valueOf(dataList.get(i).get(j));
// }else {
// if (String.valueOf(dataList.get(i).get(j)).equals("null")){
// rowData[j]=Float.valueOf(0);
// }else {
// rowData[j]=Float.valueOf(String.valueOf(dataList.get(i).get(j)));
// }
// }
// }
// writer.addRecord(rowData);
// }
// // 写入数据
// writer.write(fos);
// } catch (IOException e) {
// e.printStackTrace();
// // 重置response
// outputErrorJson(response,e.getMessage());
// }
// }
/**
* 这个是通用的easyexcel无对象导出方式,使用这个方式需要调用方法前设置ContentType类型
* @param fileName 导出的文件名+文件后缀
* @param response HttpServletResponse
* @param dataList 需要导出的行数据
* @param headList 需要导出的列数据
* @throws Exception
*/
public static void exportEasyExcel(String fileName, List<List<String>> headList, List<List<Object>> dataList, HttpServletResponse response) throws IOException {
try {
// response.setContentType("application/x-dbf;charset=UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//设置列名的字体大小
WriteFont headWriteFont = new WriteFont();
//设置字体大小为10
headWriteFont.setFontHeightInPoints((short) 10);
//取消加粗
headWriteFont.setBold(false);
//设置字体为Arial
headWriteFont.setFontName("Arial");
//列名单元的风格对象
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setWriteFont(headWriteFont);
//设置前景色为白色
// headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//去除列名边框
headWriteCellStyle.setBorderTop(BorderStyle.NONE);
headWriteCellStyle.setBorderLeft(BorderStyle.NONE);
headWriteCellStyle.setBorderRight(BorderStyle.NONE);
headWriteCellStyle.setBorderBottom(BorderStyle.NONE);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy();
horizontalCellStyleStrategy.setHeadWriteCellStyle(headWriteCellStyle);
WriteCellStyle cellStyle=new WriteCellStyle();
WriteFont cellWriteFont = new WriteFont();
cellWriteFont.setFontHeightInPoints((short) 10);
cellWriteFont.setFontName("宋体");
cellStyle.setWriteFont(cellWriteFont);
List<WriteCellStyle> writeCellStyleList = new ArrayList<>();
writeCellStyleList.add(cellStyle);
horizontalCellStyleStrategy.setContentWriteCellStyleList(writeCellStyleList);
EasyExcel.write(response.getOutputStream()).registerWriteHandler(horizontalCellStyleStrategy).head(headList).autoCloseStream(Boolean.FALSE).sheet("sheet").doWrite(dataList);
} catch (IOException e) {
e.printStackTrace();
// 重置response
outputErrorJson(response,e.getMessage());
}
}
public static void outputErrorJson(HttpServletResponse response,String message) throws IOException {
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + message);
response.getWriter().println(JSON.toJSONString(map));
}
/**
* 这个是通用的easyexcel有对象导出方式
* @param response HttpServletResponse
* @param type 导出excel后缀类型
* @param fileName 导出文件名
* @param clazz 列表中的类型对象
* @param list 导出列表
* @throws Exception
*/
public static <T> void easyExcelObjectToExcel(HttpServletResponse response,String fileName,String type, Class<T> clazz,List<T> list) throws IOException {
if ("csv".equals(type)){
response.setContentType("text/csv");
}else if("dbf".equals(type)){
response.setContentType("application/x-dbf");
}else if("xls".equals(type)){
response.setContentType("application/vnd.ms-excel");
}else {
//默认xlsx
type="xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName+"."+type, "utf-8"));
try {
HorizontalCellStyleStrategy horizontalCellStyleStrategy = setMyCellStyle();
EasyExcel.write(response.getOutputStream(), clazz).sheet("Sheel1").registerWriteHandler(horizontalCellStyleStrategy).doWrite(list);
} catch (IOException e) {
e.printStackTrace();
outputErrorJson(response, e.getMessage());
}
}
public static HorizontalCellStyleStrategy setMyCellStyle() {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 颜色
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 10);
// 字体
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setWrapped(true);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置内容靠中对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
return horizontalCellStyleStrategy;
}
/**
* 这个是通用的easyPoi有对象导出方式
* @param response HttpServletResponse
* @param type 导出excel后缀类型
* @param fileName 导出文件名
* @param clazz 列表中的类型对象
* @param list 导出列表
* @throws Exception
*/
public static <T> void easyPoiObjectToExcel(HttpServletResponse response,String fileName, String type, Class<T> clazz, List<T> list) throws IOException {
if ("csv".equals(type)){
response.setContentType("text/csv");
}else if("dbf".equals(type)){
response.setContentType("application/x-dbf");
}else if("xls".equals(type)){
response.setContentType("application/vnd.ms-excel");
}else {
//默认xlsx
type="xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + type, "utf-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
try {
ExportParams exportParams = new ExportParams(fileName, "Sheel1");
exportParams.setStyle(ExcelStylesUtil.class);
// 生成workbook 并导出
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
//获取sheet对象
Sheet sheet = workbook.getSheetAt(0);
//去除窗口冻结
sheet.createFreezePane(0,0);
workbook.write(response.getOutputStream());
workbook.close();
} catch (IOException e) {
e.printStackTrace();
outputErrorJson(response, e.getMessage());
}
}
}
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!