POI操作(xls、csv、txt)

介绍一下POI操作的一个非常好的工具,easyPOI,网址:http://easypoi.mydoc.io/#category_49976

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依赖:

<!--进行excel、word操作的poi jar包-->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.9</version>
</dependency>
<!--一个非常好的工具jar包-->
<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>4.0.0</version>
</dependency>


<!--必须引入的包,操作CSV-->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-csv</artifactId>
	<version>1.5</version>
</dependency>

导出方法流程:(导出为CSV和TXT是一样的,只需要将文件的后缀名修改即可)

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);
    }

}

 

import org.apache.commons.lang3.ObjectUtils;

import java.util.HashMap;

/**
 * 操作消息提醒
 *
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    public static final String CODE_TAG = "code";

    /**
     * 返回内容
     */
    public static final String MSG_TAG = "msg";

    /**
     * 数据对象
     */
    public static final String DATA_TAG = "data";

    /**
     * 状态类型
     */
    public enum Type {
        /**
         * 成功
         */
        SUCCESS(0),
        SUCCESS_IMG_BYTE(201),
        /**
         * 警告
         */
        WARN(301),
        /**
         * 错误
         */
        ERROR(500);
        private final int value;

        Type(int value) {
            this.value = value;
        }

        public int value() {
            return this.value;
        }
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
     */
    public AjaxResult() {
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     *
     * @param type 状态类型
     * @param msg  返回内容
     */
    public AjaxResult(Type type, String msg) {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     *
     * @param type 状态类型
     * @param msg  返回内容
     * @param data 数据对象
     */
    public AjaxResult(Type type, String msg, Object data) {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
        if (ObjectUtils.isNotEmpty(data)) {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     *
     * @return 成功消息
     */
    public static AjaxResult success() {
        return AjaxResult.success("操作成功");
    }

    /**
     * 返回成功数据
     *
     * @return 成功消息
     */
    public static AjaxResult success(Object data) {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @return 成功消息
     */
    public static AjaxResult success(String msg) {
        return AjaxResult.success(msg, null);
    }

    /**
     * 返回成功消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static AjaxResult success(String msg, Object data) {
        return new AjaxResult(Type.SUCCESS, msg, data);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult warn(String msg) {
        return AjaxResult.warn(msg, null);
    }

    /**
     * 返回警告消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult warn(String msg, Object data) {
        return new AjaxResult(Type.WARN, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @return
     */
    public static AjaxResult error() {
        return AjaxResult.error("操作失败");
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult error(String msg) {
        return AjaxResult.error(msg, null);
    }

    /**
     * 返回错误消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult error(String msg, Object data) {
        return new AjaxResult(Type.ERROR, msg, data);
    }
}

前端操作:(两步请求,第一步是请求拿取数据,后台生成文件,返回文件路径,第二部请求文件返回输出流下载文件)

 

将Python中爬取的POI数据存储到CSV文件中非常简单。以下是一个基本的步骤: 1. 首先,你需要在Python中打开一个CSV文件,并准备写入数据。你可以使用Python内置的CSV模块来实现这一点,例如: ```python import csv with open('poi_data.csv', mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(['name', 'latitude', 'longitude', 'category']) ``` 在这个例子中,我们创建了一个名为`poi_data.csv`的新文件,并写入了一个标题行。 2. 接下来,你需要将每个POI的数据写入CSV文件中。你可以使用`writerow`方法将数据写入文件。例如,如果你的POI数据是一个Python列表,其中每个元素包含名称、纬度、经度和类别信息,你可以使用以下代码将其写入CSV文件: ```python import csv poi_data = [ ['POI 1', 39.9087, 116.3975, 'Restaurant'], ['POI 2', 39.9138, 116.3636, 'Hotel'], ['POI 3', 39.9230, 116.3883, 'Attraction'] ] with open('poi_data.csv', mode='a', newline='') as file: writer = csv.writer(file) for poi in poi_data: writer.writerow(poi) ``` 在这个例子中,我们打开了一个名为`poi_data.csv`的现有文件,并将每个POI的数据写入文件中。我们使用`a`模式打开文件,这意味着我们将数据追加到文件的末尾。 3. 最后,记得在程序结束时关闭CSV文件。你可以在文件处理完成后使用`close`方法来关闭文件,或者使用Python的`with`语句来自动关闭文件。例如,如果你在第一步中使用了`with`语句来打开CSV文件,那么文件将在代码块结束时自动关闭。 希望这可以帮助你将Python中爬取的POI数据存储到CSV文件中!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值