读取mysql中的数据并存入csv文件中

1、导入的jar包

        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>

2、公共返回类R

@Data
@NoArgsConstructor
public class R<T> {
    private int code;
    private String msg;
    private T data;


    public static R ok(){
        R r = new R();
        r.setCode(200);
        r.setMsg("成功");
        return r;
    }
    public static R error(){
        R r = new R();
        r.setCode(444);
        r.setMsg("失败");
        return r;
    }


    public R data(T data){
        this.setData(data);
        return this;
    }
}

3、csv工具类

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;
import com.csvreader.CsvWriter;
import lombok.extern.slf4j.Slf4j;

/**
 * 类名称: CsvUtil
 * 类描述: 文件操作
 */
@Slf4j
public class CsvUtil {

    /**
     *  Description: 将List<T>类型数据以csv存储至本地
     *  list:list<T>
     *  csvFilePath: 如D:/XXX/DATA20190821.csv
     *  csvHeaders:表头
     */
    public static <T> void writeCSV(Collection<T> list,String csvFilePath,String[] csvHeaders) {
        try {
            log.info("<--------CSV文件开始写入-------->");
            // 定义路径,分隔符,编码
            CsvWriter csvWriter = new CsvWriter(csvFilePath, ',',  Charset.forName("UTF-8"));
            // 写表头
            csvWriter.writeRecord(csvHeaders);
            // 写内容
            //遍历集合
            Iterator<T> it = list.iterator();
            while (it.hasNext()) {
                T t = (T) it.next();
                //获取类属性
                Field[] fields = t.getClass().getDeclaredFields();
                String[] csvContent=new String[fields.length];
                for (short i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    String fieldName = field.getName();
                    String getMethodName = "get"
                            + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);
                    try {
                        Class tCls = t.getClass();
                        Method getMethod =  tCls.getMethod(getMethodName,new Class[] {});
                        Object value = getMethod.invoke(t, new Object[]  {});
                        if (value == null) {
                            continue;
                        }
                        //取值并赋给数组
                        String textvalue= value.toString();
                        csvContent[i]= textvalue;
                    }catch (Exception e) {
                        e.getStackTrace();
                    }
                }
                //迭代插入记录
                csvWriter.writeRecord(csvContent);
            }
            csvWriter.close();
            log.info("<--------CSV文件写入成功-------->");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

4、测试

@RestController
@RequestMapping("/csv")
public class CsvController {
    @Autowired
    private ChinaService chinaService;

    @GetMapping("/mysqlToCsv")
    public R mysqlToCsv(){
        // 从mysql中查数据
        List<China> list = chinaService.getAll();

        //1.设置存储路径和文件名
        String filePath="D:\\china.csv";
        //2.表头 ( 表头数组中的数据一般与数据库表中的字段名对应 )
        String[] csvHeaders =  {"fid","the_geom","sheng"};
        CsvUtil.writeCSV(list,filePath,csvHeaders);
        return R.ok();
    }
}

5、结果

在这里插入图片描述
在这里插入图片描述
这里乱码了,可能是因为csv文件编码格式不一样,我用文本打开就没有乱码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要用Java代码读取MySQL导出的CSV文件并在Vue上使用高德地图表示它们,您需要完成以下步骤: 1. 使用Java代码读取CSV文件并将其转换为Java对象。 2. 使用Java对象的地理位置信息调用高德地图Web服务API,将其转换为高德地图的经纬度坐标。 3. 将转换后的数据作为JSON格式的数据传递给Vue组件,并在Vue组件使用高德地图API将它们在地图上表示。 下面是一个简单的Java代码示例,可以将包含地理位置信息的CSV文件转换为高德地图的经纬度坐标,并将它们作为JSON格式的数据传递给Vue组件: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.amap.api.maps.model.LatLng; public class LocationLoader { private static final String CSV_FILE = "locations.csv"; private static final String API_KEY = "your_api_key"; public static void main(String[] args) { // 读取CSV文件 List<Location> locations = readCsvFile(CSV_FILE); // 将地理位置信息转换为经纬度坐标 for (Location location : locations) { LatLng latLng = geocodeLocation(location.getAddress()); location.setLatitude(latLng.latitude); location.setLongitude(latLng.longitude); } // 将转换后的数据作为JSON格式的数据传递给Vue组件 JSONArray jsonArray = new JSONArray(); for (Location location : locations) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", location.getName()); jsonObject.put("address", location.getAddress()); jsonObject.put("latitude", location.getLatitude()); jsonObject.put("longitude", location.getLongitude()); jsonArray.add(jsonObject); } System.out.println(jsonArray.toJSONString()); } private static List<Location> readCsvFile(String fileName) { List<Location> locations = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { String[] values = line.split(","); locations.add(new Location(values[0], values[1])); } } catch (IOException e) { e.printStackTrace(); } return locations; } private static LatLng geocodeLocation(String address) { AMap amap = new AMap(API_KEY); JSONObject json = amap.geocode(address); return new LatLng(json.getJSONObject("location").getDouble("lat"), json.getJSONObject("location").getDouble("lng")); } } class Location { private String name; private String address; private double latitude; private double longitude; public Location(String name, String address) { this.name = name; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } } ``` 在上面的代码,我们使用了高德地图的Java SDK(amap)来将地理位置信息转换为经纬度坐标,需要先在高德地图开发者心申请API Key,并将其替换为代码的“your_api_key”部分。 完成了上述步骤后,您可以将转换后的JSON格式的数据传递给Vue组件,例如: ```javascript <template> <div id="map-container"></div> </template> <script> import AMapLoader from '@amap/amap-jsapi-loader'; export default { name: 'MapComponent', async mounted() { // 加载高德地图API await AMapLoader.load({ key: 'your_api_key', version: '2.0', plugins: ['AMap.Marker'], }); // 加载地理位置信息 const response = await fetch('locations.json'); const locations = await response.json(); // 在地图上添加标记 const map = new AMap.Map('map-container', { zoom: 10, }); locations.forEach((location) => { const marker = new AMap.Marker({ position: [location.longitude, location.latitude], title: location.name, }); marker.setMap(map); }); }, }; </script> ``` 在上面的代码,我们使用了@amap/amap-jsapi-loader库来异步加载高德地图API,并在Vue组件使用高德地图API将地理位置信息在地图上表示。需要先在高德地图开发者心申请API Key,并将其替换为代码的“your_api_key”部分。 请注意,在使用高德地图的API时,需要遵守高德地图的相关使用条款和隐私政策。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值