POI操作(xls、csv、txt)
程序员文章站
2022-05-27 11:57:41
...
poi的基本操作:https://www.cnblogs.com/gdwkong/p/8669220.html
上面的链接介绍了如何对导入导出xls格式的excel文件进行操作,但是有时候我们在实际中不仅要支持xls等传统的报表格式进行导入导出操作,还需要进行csv格式数据的导出及txt等格式的导出导入操作,因为当导出数据量非常大的时候,这时候很多就会选择csv格式导出,csv导出数据没有任何格式,就是用逗号分隔符和换行符组成的数据。
一、导出CSV格式数据及TXT格式数据(http://commons.apache.org/proper/commons-csv/user-guide.html)
引入maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
导出方法流程:
public static void writeCsv(String[] headers, List<String[]> data, String filePath) throws IOException {
//初始化csvformat
CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
//创建FileWriter对象
FileWriter fileWriter=new FileWriter(filePath);
//创建CSVPrinter对象
try (CSVPrinter printer = new CSVPrinter(fileWriter, formator)) {
//写入列头数据
printer.printRecord(headers);
if (null != data) {
//循环写入数据
for (String[] lineData : data) {
printer.printRecord(lineData);
}
}
}catch (Exception e){
}
System.out.println("CSV文件创建成功,文件路径:"+filePath);
}
public static void main(String[] args) {
String[] headers = {"名字","年龄","出生地"};
List<String[]> data = new ArrayList<>();
data.add(new String[]{"小明","22","重庆"});
data.add(new String[]{"小红","18","南充"});
data.add(new String[]{"小强","20","成都"});
try {
writeCsv(headers, data, "E:/text.csv");
} catch (IOException e) {
e.printStackTrace();
}
}
工具类:(poi相关)
/**
* 自定义注解
*
* @author
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* 导出到Excel中的名字.
*/
public abstract String name();
}
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
*
* * @projectName ry
* * @title ExcelAndCsvForMat
* * @package com.ruoyi.common.utils.poi
* * @description 该类的作用描述,必填
* * @author IT_CREAT
* * @date 2019 2019/8/14 15:58
* * @version V1.0.0
*
*/
@Data
@NoArgsConstructor
public class ExcelAndCsvForMat<T> {
public static final Integer xls = 0;
public static final Integer csv = 1;
public static final Integer txt = 2;
/**
* 最终得到的该行数据
*/
private List<String> rowContent;
/**
* 设置行数数据格式(说明:类似于list集合的add)通过getColumnContent()方法可以得到该行数据集
* @param content 内容
* @param rightIntervalColumnNumber 右侧间隔列数
*/
public void addContentAndRightIntervalColumnNumber(String content,Integer rightIntervalColumnNumber) {
if(!StringUtils.isEmpty(content) && !ObjectUtils.isEmpty(rightIntervalColumnNumber)){
List<String> columnContentArray = null;
if(!CollectionUtils.isEmpty(this.rowContent)){
columnContentArray = this.rowContent;
columnContentArray.add(content);
for(int i= 0;i<rightIntervalColumnNumber;i++){
columnContentArray.add("");
}
}else {
columnContentArray = new ArrayList<>();
columnContentArray.add(content);
for(int i= 0;i<rightIntervalColumnNumber;i++){
columnContentArray.add("");
}
this.rowContent = columnContentArray;
}
}
}
/**
* 得到列头不显示数据
* @param fields
* @return
*/
public Object[] getTransferHeader(List<Field> fields, Map<String,String> columnName) {
List<String> strHeader = null;
if(!CollectionUtils.isEmpty(fields)){
strHeader = new ArrayList<>();
for (Field field : fields){
Excel attr = field.getAnnotation(Excel.class);
if(ObjectUtils.isEmpty(columnName)){
strHeader.add(attr.name());;// 写入列名
}else {
if(columnName.containsKey(field.getName())){
strHeader.add(columnName.get(field.getName()));// 写入列名
}else {
strHeader.add(attr.name());;// 写入列名
}
}
}
}
if(strHeader != null){
return strHeader.toArray();
}
return null;
}
public Object[] getTransferRowData(T object,List<Field> fields) {
List<String> data = null;
if(!CollectionUtils.isEmpty(fields)){
data = new ArrayList<>();
for(Field field:fields){
String s = object2Str(field, object);
data.add(s);
}
return data.toArray();
}
return null;
}
public String object2Str(Field field,T vo){
field.setAccessible(true); // 设置实体类私有属性可访问
if(field.getType() == Date.class){
String dateToStr = "";
try {
dateToStr = DateUtils.parseDateToStr("yyyy-MM-dd", (Date) field.get(vo));
return dateToStr;
} catch (Exception e) {
try {
dateToStr = DateUtils.parseDateToStr("yyyy-MM-dd hh:mm:ss", (Date) field.get(vo));
} catch (Exception ex) {
try {
dateToStr = DateUtils.parseDateToStr("yyyy-MM", (Date) field.get(vo));
} catch (Exception exc) {
}
}
}
return dateToStr;
}
try {
return String.valueOf(field.get(vo));
}catch (Exception e){
return "";
}
}
}
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
*
* * @projectName ry
* * @title CsvUtil
* * @package com.ruoyi.common.utils.poi
* * @description 导出成CSV 文件工具
* * @author IT_CREAT
* * @date 2019 2019/8/14 14:18
* * @version V1.0.0
*
*/
public class CsvUtil<T>{
private final static String NEW_LINE_SEPARATOR="\n";
public Class<T> clazz;
public CsvUtil(Class<T> clazz) {
this.clazz = clazz;
}
public static CsvUtil create(){
return new CsvUtil(null);
}
/**写入csv文件
* @param headers 列头
* @param data 数据内容
* @param filePath 创建的csv文件路径
* @throws IOException **/
public static void writeCsv(String[] headers, List<String[]> data, String filePath) throws IOException {
//初始化csvformat
CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
//创建FileWriter对象
FileWriter fileWriter=new FileWriter(filePath);
//创建CSVPrinter对象
try (CSVPrinter printer = new CSVPrinter(fileWriter, formator)) {
//写入列头数据
printer.printRecord(headers);
if (null != data) {
//循环写入数据
for (String[] lineData : data) {
printer.printRecord(lineData);
}
}
}catch (Exception e){
}
System.out.println("CSV文件创建成功,文件路径:"+filePath);
}
/**
* 导出成为CSV格式数据
* @param list 数据库查询出来的数据集合
* @param fileName 文件名称
* @param firstCondition 第一行显示内容,一般为查询条件
* @param excludeColumnName 在excel注解基础上需要排除的字段
* @param columnName 在excel注解基础上需要重写列的中文显示名的字段
* @param lastCondition 第一行显示内容,一般为合计之类的
* @return
*/
public AjaxResult exportCsv(List<T> list, String fileName, List<String> firstCondition, List<String> excludeColumnName, Map<String,String> columnName, List<String> lastCondition,String suffix){
Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
List<Field> fields = new ArrayList<Field>();
// 得到所有field并存放到一个list中.
for (Field field : allFields) {
if (field.isAnnotationPresent(Excel.class)) {
if(CollectionUtils.isEmpty(excludeColumnName)){
fields.add(field);
}else if(!CollectionUtils.isEmpty(excludeColumnName) && !excludeColumnName.contains(field.getName())){
fields.add(field);
}
}
}
AjaxResult ajaxResult = null;
//创建FileWriter对象
try {
//初始化csvformat
CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
//创建输出流
String filename = encodingFilename(fileName,suffix);
String filePath = getfile() + filename;
FileWriter fileWriter = new FileWriter(filePath);
//创建CSVPrinter流
try (CSVPrinter printer = new CSVPrinter(fileWriter, formator)){
//写入第一列条件
if(!CollectionUtils.isEmpty(firstCondition)){
printer.printRecord(firstCondition);
}
ExcelAndCsvForMat<T> tExcelAndCsvForMat = new ExcelAndCsvForMat<>();
//写入列头
Object[] transferHeader = tExcelAndCsvForMat.getTransferHeader(fields, columnName);
printer.printRecord(transferHeader);
//写入数据集
if(!CollectionUtils.isEmpty(list)){
for (T object : list){
Object[] transferRowData = tExcelAndCsvForMat.getTransferRowData(object, fields);
printer.printRecord(transferRowData);
}
}
//写入列尾部内容
if(!CollectionUtils.isEmpty(lastCondition)){
printer.printRecord(lastCondition);
}
ajaxResult = AjaxResult.success(filename);
fileWriter.close();
}catch (Exception e){
ajaxResult = AjaxResult.error("导出数据失败,请联系管理员");
}
} catch (Exception e) {
ajaxResult = AjaxResult.error("导出数据失败,请联系管理员");
}
return ajaxResult;
}
public AjaxResult exportMap(List<Map<String,Object>> list, Map<String, String> columnAndChineseNameMap, String fileName,String suffix) {
AjaxResult ajaxResult = null;
//创建FileWriter对象
try {
//初始化csvformat
CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
//创建输出流
String filename = encodingFilename(fileName,suffix);
String filePath = getfile() + filename;
FileWriter fileWriter = new FileWriter(filePath);
//创建CSVPrinter流
try (CSVPrinter printer = new CSVPrinter(fileWriter, formator)){
//写入列头
if(!ObjectUtils.isEmpty(columnAndChineseNameMap)){
List<String> head = new ArrayList<>();
for(String key: columnAndChineseNameMap.keySet()){
head.add(columnAndChineseNameMap.get(key));
}
printer.printRecord(head.toArray());
}
//写入数据集
if(!CollectionUtils.isEmpty(list)){
for (Map map : list){
List<Object> colum = new ArrayList<>();
for(String key: columnAndChineseNameMap.keySet()){
if(map.containsKey(key)){
colum.add(map.get(key));
}
}
printer.printRecord(colum.toArray(new Object[colum.size()]));
}
}
ajaxResult = AjaxResult.success(filename);
fileWriter.close();
}catch (Exception e){
ajaxResult = AjaxResult.error("导出数据失败,请联系管理员");
}
} catch (Exception e) {
ajaxResult = AjaxResult.error("导出数据失败,请联系管理员");
}
return ajaxResult;
}
/**
* 编码文件名
*/
public String encodingFilename(String filename,String suffix) {
filename = UUID.randomUUID().toString() + "_" + filename + "."+suffix;
return filename;
}
public String getfile() {
//return ResourceUtils.getURL("classpath:").getPath() + "static/file/";
return System.getProperty("java.io.tmpdir") + System.getProperty("file.separator");
}
public static void main(String[] args) {
String[] headers = {"名字","年龄","出生地","","小明"};
List<String[]> data = new ArrayList<>();
data.add(new String[]{"小明","22","重庆"});
data.add(new String[]{"小红","18","南充"});
data.add(new String[]{"小强","20","成都"});
try {
writeCsv(headers, data, "E:/text.csv");
} catch (IOException e) {
e.printStackTrace();
}
}
}
日期相关:
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.ObjectUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 时间工具类
*
* @author ruoyi
*/
public class DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
if (!ObjectUtils.isEmpty(date)) {
return new SimpleDateFormat(format).format(date);
}
return "";
}
public static final Date dateTime(final String format, final String ts) {
if(!StringUtils.isBlank(ts)){
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
return null;
}
/**
* 获取开始时间
*
* @param startTime
* @return
* @author DurantSimpson
*/
public static final Date getStartTime(final String startTime) {
try {
return new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS).parse(startTime + " 00:00:00");
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 获取结束时间
*
* @param endTime
* @return
* @author DurantSimpson
*/
public static final Date getEndTime(final String endTime) {
try {
return new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS).parse(endTime + " 23:59:59");
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年/月/日 如20180808
* @param
* @param
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
public static String getDistanceTime(long time1, long time2) {
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
if (day != 0) return day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
if (hour != 0) return hour + "小时" + min + "分钟" + sec + "秒";
if (min != 0) return min + "分钟" + sec + "秒";
if (sec != 0) return sec + "秒";
return "0秒";
}
/**
*
* 描述:获取上个月的最后一天.
*
* @return
*/
public static String getLastMaxMonthDate() {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
/**
*
* 描述:获取前1天的时间
*
* @return
*/
public static Date getBefore1(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,-1);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取前2天的时间
*
* @return
*/
public static Date getBefore2(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,-2);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取前3天的时间
*
* @return
*/
public static Date getBefore3(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,-3);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取后1天的时间
*
* @return
*/
public static Date getAfter1(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,1);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取后2天的时间
*
* @return
*/
public static Date getAfter2(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,2);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取后3天的时间
*
* @return
*/
public static Date getAfter3(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,3);
Date time = calendar.getTime();
return time;
}
/**
*
* 描述:获取上个月月份
*
* @return
*/
public static String getLastMonthDate() {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
/**
*
* 描述:获取指定上一个月份的最后一天.
*
* @return
*/
public static String getLastMaxPointMonthDate(Date date) {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
/**
*
* 描述:获取指定日期上一个月的月份
*
* @return
*/
public static String getLastMonth(Date date) {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
/**
* 获得指定日期的前一天
* @param specifiedDay
* @return
*/
public static String getSpecifiedDayBefore(String specifiedDay){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day-1);
String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayBefore;
}
/**
* 获得指定日期的后一天
* @param specifiedDay
* @return
*/
public static String getSpecifiedDayAfter(String specifiedDay){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day+1);
String dayAfter=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayAfter;
}
public static String dateTimestamp() {
Date date = new Date();
return String.valueOf(date.getTime());
}
public static void main(String[] args) {
System.out.println(DateUtils.getLastMonth(DateUtils.dateTime("yyyy-MM","2017-1")));
System.out.println(getSpecifiedDayBefore("2019-8-1"));
Long test1 = new Long(2);
Long test2 = new Long(2);
Map<Long,Long> map = new HashMap<>();
map.put(test1,1L);
map.put(test2,2L);
System.out.println(map);
}
}
前端操作:(两步请求,第一步是请求拿取数据,后台生成文件,返回文件路径,第二部请求文件返回输出流下载文件)
上一篇: MyBatis Plus代码生成器模板
下一篇: chrome input标签自动填充