자바 작업 csv 문서 유 니 버 설 도구 클래스
18845 단어 자바 도구 클래스
package cn.com.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author: Rodge
* @time: 2017 12 25 9:39:18
* @version: V1.0.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CSVField {
/**
* CSV
*/
public String name() default "";
}
csv 도구 클래스
package cn.com.javatest.utils;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.util.ReflectionUtils;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import cn.com.javatest.annotation.CSVField;
/**
* CSV
*
* @author: Rodge
* @time: 2017 12 25 10:02:08
* @version: V1.0.0
*/
public final class CSVUtils {
/** **/
private static final Logger LOGGER = Logger.getLogger(CSVUtils.class);
/** **/
private static final String TEMP_PATH = "temp.csv";
/** **/
private CSVUtils() { }
/**
* CSV
*
* @param filePath , :D:/temp/test.csv
* @param beans
*/
public static void createCSVFile(String filePath, List beans) {
CsvWriter writer = null;
try {
//
createDir(filePath);
//
writer = new CsvWriter(filePath, ',', Charset.forName("GBK"));
//
List contents = getStringArrayFromBean(beans);
//
for (String[] each : contents) {
writer.writeRecord(each, true);
}
} catch (Exception e) {
LOGGER.error(" CSV ", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* CSV
*
* @param request
* @param response
* @param beans
*/
public static void exportCSVFile(HttpServletRequest request, HttpServletResponse response, List beans) {
String path = request.getServletContext().getRealPath("/");
try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {
//
CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));
//
List contents = getStringArrayFromBean(beans);
//
for (String[] each : contents) {
writer.writeRecord(each, true);
}
writer.close();
//
ServletOutputStream output = response.getOutputStream();
//
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
int len = -1;
byte[] b = new byte[1024 * 1024];
while((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.close();
} catch (Exception e) {
LOGGER.error(" CSV ", e);
} finally {
deleteFile(path, TEMP_PATH);
}
}
/**
* CSV
*
* @param request
* @param response
* @param beans
* @param fileName , :
*/
public static void exportCSVFile(HttpServletRequest request, HttpServletResponse response, List beans, String fileName) {
String path = request.getServletContext().getRealPath("/");
try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {
//
CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));
//
List contents = getStringArrayFromBean(beans);
//
for (String[] each : contents) {
writer.writeRecord(each, true);
}
writer.close();
//
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
int len = -1;
byte[] b = new byte[1024 * 1024];
while((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.close();
} catch (Exception e) {
LOGGER.error(" CSV ", e);
} finally {
deleteFile(path, TEMP_PATH);
}
}
/**
* CSV
*
* @param request
* @param response
* @param beans
*/
public static void exportCSVTemplate(HttpServletRequest request, HttpServletResponse response, Class clazz) {
//
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
exportCSVTemplate(request, response, clazz, fileName);
}
/**
* CSV
*
* @param request
* @param response
* @param beans
* @param fileName
*/
public static void exportCSVTemplate(HttpServletRequest request, HttpServletResponse response, Class clazz, String fileName) {
String path = request.getServletContext().getRealPath("/");
try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {
//
CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));
//
Field[] declaredFields = clazz.getDeclaredFields();
List annoFields = new ArrayList();
for (Field field : declaredFields) {
CSVField anno = field.getAnnotation(CSVField.class);
if (anno != null) {
annoFields.add(field);
}
}
// ,
String[] title = new String[annoFields.size()];
for (int i = 0; i < annoFields.size(); i++) {
title[i] = annoFields.get(i).getAnnotation(CSVField.class).name();
}
//
if (ArrayUtils.isNotEmpty(title)) {
writer.writeRecord(title);
}
writer.close();
//
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
int len = -1;
byte[] b = new byte[1024 * 1024];
while((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.close();
} catch (Exception e) {
LOGGER.error(" CSV ", e);
} finally {
deleteFile(path, TEMP_PATH);
}
}
/**
* CSV
*
* @param filePath , :D:/csv/xxx.csv
* @param bean
* @return List
*/
public static List readCSVFile(String filePath, Class bean) {
List dataList = new ArrayList();
CsvReader reader = null;
try {
// CSV :CsvReader( , , );
reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
if (reader != null) {
// , ,
//reader.readHeaders();
//
while (reader.readRecord()) {
dataList.add(reader.getValues());
}
if (!dataList.isEmpty()) {
//
return getBeanFromStringArray(dataList, bean);
}
}
} catch (Exception e) {
LOGGER.error(" CSV ", e);
} finally {
if (reader != null) {
reader.close();
}
}
return Collections.emptyList();
}
/**
*
*
* @param filePath , :d:/test
*/
public static boolean deleteFiles(String filePath) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
if (f.isFile() && f.delete()) {
LOGGER.info(" " + f.getName() + " ");
}
}
return true;
}
}
return false;
}
/**
*
*
* @param filePath , :d:/test
* @param fileName , :110.csv
*/
public static boolean deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
if (f.isFile() && f.getName().equals(fileName)) {
return f.delete();
}
}
}
}
return false;
}
/**
*
*
* @param beans
* @return List
*/
private static List getStringArrayFromBean(List beans) {
List result = new ArrayList();
Class extends Object> cls = beans.get(0).getClass();
Field[] declaredFields = cls.getDeclaredFields();
List annoFields = new ArrayList();
//
for (Field field : declaredFields) {
CSVField anno = field.getAnnotation(CSVField.class);
if (anno != null) {
annoFields.add(field);
}
}
// ,
String[] title = new String[annoFields.size()];
for (int i = 0; i < annoFields.size(); i++) {
title[i] = annoFields.get(i).getAnnotation(CSVField.class).name();
}
result.add(title);
try {
//
for (T t : beans) {
String[] item = new String[annoFields.size()];
int index = 0;
for (Field field : annoFields) {
Class> valType = field.getType();
String fieldName = field.getName();
String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method method = ReflectionUtils.findMethod(t.getClass(), methodName);
if (method != null) {
Object value = ReflectionUtils.invokeMethod(method, t);
item[index] = setValues(value, valType);
}
index ++;
}
result.add(item);
}
} catch (Exception e) {
LOGGER.info(" ", e);
}
return result;
}
/**
*
*
* @param dataList
* @param bean
* @return List
*/
private static List getBeanFromStringArray(List dataList, Class bean) {
List list = new ArrayList<>();
List
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 작업 csv 문서 유 니 버 설 도구 클래스텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.