CsvUtils.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package cn.com.ctop.common.utils;
  2. import com.csvreader.CsvReader;
  3. import com.csvreader.CsvWriter;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.nio.charset.Charset;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. public class CsvUtils {
  10. public static void checkandCreateFile(String outPath) {
  11. File file = new File(outPath);
  12. try {
  13. if (!file.exists()) {
  14. file.createNewFile();
  15. System.out.println("文件不存在,新建成功!");
  16. } else {
  17. System.out.println("文件存在!");
  18. }
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. public static List<String[]> readCSV(String inPath, String charset) throws IOException {
  24. List<String[]> list = new ArrayList<>();
  25. CsvReader reader = new CsvReader(inPath, ',', Charset.forName(charset));
  26. reader.readHeaders();
  27. while (reader.readRecord()) {
  28. list.add(reader.getValues());
  29. }
  30. reader.close();
  31. for (int row = 0; row < list.size(); row++) {
  32. int length = list.get(row).length;
  33. if (length > 0) {
  34. for (int i = 0; i < length; i++) {
  35. System.out.print(list.get(row)[i] + ",");
  36. }
  37. }
  38. System.out.println("");
  39. }
  40. return list;
  41. }
  42. public static void writeCSV(String outPath, List<String[]> data) throws IOException {
  43. CsvUtils.checkandCreateFile(outPath);
  44. CsvWriter wr = new CsvWriter(outPath, ',', Charset.forName("gb2312"));
  45. String[] header = {"Name", "Province", "City", "Address", "Tel", "Website", "Server_content", "Jigou_cengji", "Type", "Parent_level1", "Parent_level2", "Branch_level"};
  46. wr.writeRecord(header);
  47. for (int i = 0; i < data.size(); i++) {
  48. String[] dataString = data.get(i);
  49. wr.writeRecord(dataString);
  50. }
  51. wr.close();
  52. }
  53. public static void main(String[] args) throws IOException {
  54. String[] header = new String[]{"日期", "plan", "广告组", "花费", "曝光数", "点击数", "行为数", "点击率", "行为率", "平均千次曝光花费", "平均点击单价", "平均行为单价", "提交按钮点击", "表单提交率", "表单提交单价"};
  55. String inPath = "D:\\工作文件\\360借条\\effect_unit_2019-08-02-00_2019-08-02-00.csv";
  56. String outPath = "D:\\工作文件\\360借条\\effect_unit_2019-08-02-00_2019-08-02-00_bak.csv";
  57. List<String[]> list = CsvUtils.readCSV(inPath, "utf8");
  58. CsvUtils.writeCSV(outPath, list);
  59. }
  60. }