如何在JavaScript中按列标题名称获取Excel表格指定列数据并转换为JSON对象
Hey there! I see you're working on extracting specific columns from an Excel file and converting them to JSON using JavaScript—let's walk through how to fix your code step by step, since you're new to JS. 😊
First, let's make sure your HTML has all the necessary elements (I'll add the dropdown you mentioned with the correct ID so we can reference it in JS):
<!-- File input --> <input type="file" id="fileUpload" accept=".xlsx, .xls"> <!-- Column selector dropdown --> <select id="columnSelector"> <option value="Name">Name</option> <option value="Email">Email</option> <option value="Address">Address</option> </select> <!-- Upload button --> <button id="uploadExcel">Upload & Convert to JSON</button> <!-- Area to display JSON output --> <pre id="jsonData"></pre> <!-- Include SheetJS (XLSX) library - required for reading Excel files --> <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
Now, let's modify your JavaScript code to capture the selected column and filter the Excel data to only include that column:
let selectedFile; // Listen for when a file is selected document.getElementById("fileUpload").addEventListener("change", function (event) { selectedFile = event.target.files[0]; }); // Listen for upload button click document.getElementById("uploadExcel").addEventListener("click", function () { // Check if a file was selected if (!selectedFile) { alert("Please select an Excel file first!"); return; } // Get the selected column name from the dropdown const selectedColumn = document.getElementById("columnSelector").value; if (!selectedColumn) { alert("Please select a column to extract!"); return; } const fileReader = new FileReader(); fileReader.onload = function (event) { const data = event.target.result; const workbook = XLSX.read(data, { type: "binary" }); // Work with the first sheet (adjust if your data is in a different sheet) const sheetName = workbook.SheetNames[0]; // Convert sheet data to an array of objects (each object is a row) const rowData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]); // Filter data to only keep the selected column const filteredData = rowData.map(row => { // Create a new object with only the selected column return { [selectedColumn]: row[selectedColumn] }; }); // Convert filtered data to formatted JSON (indent for readability) const jsonOutput = JSON.stringify(filteredData, null, 2); // Display JSON on the page document.getElementById("jsonData").textContent = jsonOutput; // Log to console for debugging console.log(jsonOutput); }; fileReader.readAsBinaryString(selectedFile); });
Key Changes & Explanations:
- Capture Selected Column: We added
const selectedColumn = document.getElementById("columnSelector").valueto get the user's chosen column from the dropdown. We also added checks to make sure the user selects both a file and a column before proceeding. - Filter Rows to Keep Only Selected Column: Using
rowData.map(row => { ... }), we iterate over each row and create a new object that only includes the selected column. The[selectedColumn]syntax is a computed property name—it lets us dynamically set the key name in the object based on the selected column. - Formatted JSON: We added
null, 2toJSON.stringify()to indent the output, making it easier to read on the page instead of a single line. - Simplified Sheet Handling: Instead of looping through all sheets (which you might not need), we just use the first sheet in the workbook (adjust this if your data is in a different sheet).
Testing This:
If you upload your sample Excel file and select "Name" from the dropdown, the output JSON will look like this:
[ { "Name": "A" }, { "Name": "B" }, { "Name": "C" }, { "Name": "D" } ]
This should exactly meet your requirement! Let me know if you run into any issues. 😎
内容的提问来源于stack exchange,提问作者Uniquedesign

