Preview a CSV In-Browser

Written
  • This uses Papa Parse to parse the first few rows of a CSV to preview it before uploading.
  • <script lang="ts">
      import Papa from 'papaparse';
      
      let columns: string|undefined;
      let previewRows: Array<Record<string, string>> = [];
      
      async function openFile(file: File|undefined) {
        if(!file) {
          return;
        }
        
        Papa.parse(file, {
          header: true,
          preview: 3, // To read first 3 data rows
          skipEmptyLines: 'greedy', // Well-formed CSV files don't need this
          complete(parsed) {
            if(parsed.errors?.[0]) {
              error = parsed.errors[0].message;
            } else if(parsed.meta.fields) {
              columns = parsed.meta.fields;
              previewRows = parsed.data;
            }
          }
        })
      }
    </script>
    
    <input 
      type="file"
      name="csvfile"
      accept=".csv,text/csv"
      on:change={(e) => openFile(e.currentTarget.files?.[0])} 
    />
    

Thanks for reading! If you have any questions or comments, please send me a note on Twitter.