user3878988
user3878988

Reputation: 841

How to change the type of a cell and other properties while exporting data to .csv using javascript

I am using below javascript code for exporting html table data to .CSV file:

var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); // csv is HTML table innerHTML data
var a = $('<a/>', {
                    style:'display:none',
                    href:csvData,
                    download: 'worksheet.csv'
                    }).appendTo('body')
                    a[0].click()
                    a.remove(); 

With this code I am able to export html table data to CSV. Now I have to achieve below requirements programmatically.

  1. I want to increase the width of a cell in generated csv file.
  2. Big number is converting to different format when it is displayed. Ex: '123456789012' is displayed as '1.23457E+11', but I want to display as '123456789012'.
  3. How to change the sheet name? Currently the sheet name is displaying as whatever file name I have given.

I want to achieve these features using javascript/jQuery or any web technologies.

Upvotes: 3

Views: 2531

Answers (1)

ADyson
ADyson

Reputation: 61784

CSV files don't have "cells". It's just a text file with some text in it, separated by commas. Open the file in Notepad or any other text editor and you'll see its true format. When you open it in Excel, Excel runs a conversion task in the background to make it display in Excel. It gets each comma-separated value and puts it into an Excel cell. The cell is an Excel concept, not a CSV one.

CSV also doesn't have sheet names. Excel will generally use the filename as the sheet name when it imports it. Also Excel will set the column widths to whatever it wants (probably the default) because the CSV file format only stores values as text - it doesn't store any formatting or data type information whatsoever.

Therefore you can't specify any of the things you want via javascript, or via any other language you might use to create a CSV, because the CSV format doesn't support them. If you open the file in Excel using the import wizard (rather than the default open method), you may be able to change some aspects of how the file is imported and displayed within Excel, but these options may or may not help you depending on your exact requirements.

Upvotes: 5

Related Questions