如何用SheetJS提取Excel文件表头并存储为数组展示?
Extract Excel Header Row with SheetJS
Hey there! Since you're just getting started with JavaScript, let's break down how to adjust your existing code to extract only the header row from the Excel file and store it in an array. Here's a modified version of your code with clear explanations:
Modified Code
$('#inputfile').change(function(e){ var reader = new FileReader(); reader.readAsArrayBuffer(e.target.files[0]); reader.onload = function(e) { var data = new Uint8Array(reader.result); var wb = XLSX.read(data,{type:'array'}); // Get the first worksheet (works for most cases; adjust if your sheet has a specific name) var targetSheet = wb.Sheets[wb.SheetNames[0]]; // Decode the sheet's cell range to know where the data starts/ends var sheetRange = XLSX.utils.decode_range(targetSheet['!ref']); // Initialize an array to store our headers var excelHeaders = []; // Loop through every column in the FIRST row (index 0) to get headers for(var colIndex = sheetRange.s.c; colIndex <= sheetRange.e.c; colIndex++){ // Create a cell address for the current header cell var cellAddress = {r: sheetRange.s.r, c: colIndex}; var cellReference = XLSX.utils.encode_cell(cellAddress); // Add the cell's value to our headers array (handle empty cells gracefully) excelHeaders.push(targetSheet[cellReference] ? targetSheet[cellReference].v : ''); } // Now you have your headers array! Let's use it: console.log('Extracted Excel Headers:', excelHeaders); // Display headers on the page (replace your full sheet HTML with a simple list) var headerDisplay = '<h3>Excel Header Preview</h3><ul>'; excelHeaders.forEach(header => { headerDisplay += `<li>${header}</li>`; }); headerDisplay += '</ul>'; $('#printHere')[0].innerHTML = headerDisplay; } });
Key Changes Explained
- Get the worksheet dynamically: Instead of hardcoding
Sheet1, we usewb.SheetNames[0]to grab the first sheet in the file (this works for most standard Excel files, but you can replace it with a specific sheet name if needed). - Extract the first row: We use
XLSX.utils.decode_rangeto get the full range of cells in the sheet, then loop through every column in the first row (indexsheetRange.s.r, which is 0 by default) to collect header values. - Handle empty cells: The ternary operator ensures that if a header cell is empty, we push an empty string to the array instead of
undefined. - Cleaner display: Instead of appending the entire sheet's HTML, we generate a simple list to show only the headers.
Quick Adjustment Tip
If your header row isn't the first row (e.g., it's the second row), just change sheetRange.s.r to the correct row index (remember, rows are zero-indexed—so second row is 1).
内容的提问来源于stack exchange,提问作者kendrickmundiz
相关产品推荐
相关产品推荐

