Skip to content

Instantly share code, notes, and snippets.

@blogscot
Created August 5, 2019 12:26
Show Gist options
  • Save blogscot/4a2d7fd480e7f9f5905eaabe251a35d8 to your computer and use it in GitHub Desktop.
Save blogscot/4a2d7fd480e7f9f5905eaabe251a35d8 to your computer and use it in GitHub Desktop.
Creating a HTML table from CSV data using D3
car name miles/gallon cylinders displacement horsepower weight acceleration model year origin
chevrolet chevelle malibu 18 8 307 130 3504 12 70 1
buick skylark 320 15 8 350 165 3693 11.5 70 1
plymouth satellite 18 8 318 150 3436 11 70 1
// Map the HTML table headings to the CSV data headings
var columns = [
{ head: 'Name', html: 'car name'},
{ head: 'Milage', html: 'miles/gallon'},
{ head: 'Cylinders', html: 'cylinders'},
{ head: 'Displacement', html: 'displacement'},
{ head: 'Horsepower', html: 'horsepower'},
{ head: 'Weight', html: 'weight'},
{ head: 'Acceleration', html: 'acceleration'},
{ head: 'Model Year', html: 'model year'},
{ head: 'Origin', html: 'origin'},
]
d3.text("data.csv").then(csvData => {
var parsedCSV = d3.csvParse(csvData);
let table = d3.select('.container')
.append("table")
.style("border-collapse", "collapse")
.style("border", "2px black solid")
table.append('thead')
.append('tr')
.selectAll('th')
.data(columns).enter()
.append('th')
.text(d => d.head)
table.append('tbody')
.selectAll('tr')
.data(parsedCSV)
.enter()
.append('tr')
.selectAll('td')
.data(row =>
columns.map(column => ({ value: row[column['html']] }))
).enter()
.append('td')
.html(d => d['value'])
.style("border", "1px black solid")
.style("padding", "10px")
.style('text-align', 'center')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment