【TypeScript】Generate and download CSVs in Shift_JIS character code.

Complete only on the front side.
CSV data is generated as string and converted with encoding-japanese.

目次

Install & load

encoding-japaneseInstall package.

npm install --save encoding-japanese

Load inimport

import Encoding from 'encoding-japanese';

For other references, see GitHub.

https://github.com/polygonplanet/encoding.js/blob/master/README_ja.md#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB

Generate CSV

Converts from Object to String CSV data.
The first argument, data, is an array of Key Values, and the map() method is used to process each element of the array.
After processing, headerString and rowItems objects are generated as strings, separated by newlines.

/**
 * Object to Csv
 * @param data
 * @param headerOrder
 * @param headerGridDisplay 表示ヘッダー切り替え
 * @returns
 */
export const objectToCsv = (
  data: Record<string, any>[],
  headerOrder: string[],
  headerGridDisplay: string[] = []
): string => {
  let headerString: string = headerOrder.join(',')
  const replacer = (_: string, value: any): any => value ?? ''
  const rowItems: string[] = data.map((row: Record<string, any>) =>
    headerOrder.map((fieldName: string) => JSON.stringify(row[fieldName], replacer)).join(',')
  )

  if (headerGridDisplay) {
    headerString = headerGridDisplay.join(',')
  }

  const csv: string = [headerString, ...rowItems].join('\r\n')

  return csv
}

Download files from your browser

The data passed as the first argument is generated as a Blob by specifying the type.
After creating the url with createObjectURL, the click() method of the a tag element is fired.

/**
 * ファイルダウンロード
 * @param data
 * @param name
 */
export const download = (data: string | Uint8Array, name: string) => {
  const blob = new Blob([data], { type: 'text/csv' })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('download', `${name}.csv`)
  a.click()
}

Convert to Shift_JIS character code and download CSV.

Generate CSV data with objectToCsv, convert the data to Shift_JIS with Encoding.convert, and pass it to downlod to download the CSV converted to Shift_JIS.

Encoding.convert requires the IntArrayType to be passed, so TextEncoder().encode is used to pass the Uint8Array type.
Specify Shift_JIS in the second argument of Encoding.convert.

const csvdata = objectToCsv(exportData, keys, headerGridDisplay)

download(
  new Uint8Array(
    Encoding.convert(new TextEncoder().encode(csvdata), {
      to: 'SJIS',
      from: 'AUTO'
    })
  ),
  `shift_jis`
)
よかったらシェアしてね!
目次