LoginSignup
1
0

CSVダウンロード自分用メモ

Last updated at Posted at 2024-04-01

  const hogeList = [
    {
      name: "malp",
      addres: "top",
      number: "333",
    },
    {
      name: "yasuo",
      addres: "mid",
      number: "222",
    },
    {
      name: "taro",
      addres: "adc",
      number: "111",
    },
  ]

  const hogeSort = "num"

  hogeList.sort((a, b) => a[hogeSort] - b[hogeSort])

  console.log(hogeList)


  /** Object の配列を受け取り CSV形式の文字列に変換する Func */
  const convertToCSV = (objArray) => {
    const array = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;

    /** 1. Objectの Key を headerとして取り出す */
    let str =
      `${Object.keys(array[0])
        .map((value) => `"${value}"`)
        .join(",")}` + "\r\n";

    // 2. 各オブジェクトの値をCSVの行として追加する
    return array.reduce((str, next) => {
      str +=
        `${Object.values(next)
          .map((value) => `"${value}"`)
          .join(",")}` + "\r\n";
      return str;
    }, str);
  };

  /** Download・処理 */
  const downloadCSV = (data, name) => {
    /** Blob Object を作成する Type. CSV */
    const blob = new Blob([data], { type: "text/csv" });
    console.log("blob", blob);
    const url = window.URL.createObjectURL(blob);
    console.log("url", url);
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", `${name}.csv`);
    a.click();
    a.remove();
  };

  /** CSVデータを作成 */
  const csvData = convertToCSV(hogeList);
  console.log(csvData);

  // CSV・Download
  downloadCSV(csvData, "hogeCsvData");
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0