Home > Software engineering >  How do take inputted values from a html form and convert to a csv?
How do take inputted values from a html form and convert to a csv?

Time:09-25

So i want to take a couple of values from an HTML input-form, and basically be able to generate a csv file to download for the user when they click a button which will consist of the data they entered into the form. However, I am confused about how i would go about this and can't find a good guide online.

I also would like to customize how the csv format will be if possible, hope somehow knows what iam trying to do! thanks.

Edit: iam not asking to do this in just html, i assume javascript is best option

CodePudding user response:

Takes all input names as columnNames and append to csv content as the first row (column names)

const columnNames = Object.keys(formObj).map(key => key.toUpperCase()).join(",");
let csvContent = "data:text/csv;charset=utf-8,";
csvContent  = columnNames   "\r\n";

Take out all form values and append to csv content.

Lets say user has entered address value as New Braunfels, TX, 78130 Since its commma separated, for this CSV will create 3 column entries New Braunfels, TX, and 78130. To handle this we will replace , with so that it will add it in one column

const formValues = Object.values(formObj).map(val => val.replaceAll(',', ' ')).join(",");
csvContent  = formValues   "\r\n";

function downloadCSV(){
    const formEl = document.forms.userForm;
    const formData = new FormData(formEl);
    const formObj = Object.fromEntries(formData);
    const columnNames = Object.keys(formObj).map(key => key.toUpperCase()).join(",");
    let csvContent = "data:text/csv;charset=utf-8,";
    csvContent  = columnNames   "\r\n";
    const formValues = Object.values(formObj).map(val => val.replaceAll(',', ' ')).join(",");
    csvContent  = formValues   "\r\n";
       // Set encoded csvContent as `href` attribute and also set download attribute to set the file name
    const encodedUri = encodeURI(csvContent);
    const link = document.querySelector("#downloadRef");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my-form-data.csv");
}
<form id="userForm">
    <div><label>Name<input type="text" name="name"></label></div>
    <div><label>Age<input type="number" name="age"></label></div>
    <div>
        Gender
        <label>Male<input type="radio" name="gender" value="male"></label>
        <label>Female<input type="radio" name="gender" value="female"></label>
    </div>
    <div><label>Address<textarea name="address"></textarea></label></div>
    <button onclick="downloadCSV()">
        <a id="downloadRef"style="text-decoration:none" href="#">Create CSV</a>
    </button>
</form>

After setting csvContent as href attribute, the click event will be taken care of by Event capturing

*This snippet will not download CSV file here, run code on your host

  • Related