如何将JSON数据导出为.xlsx格式?现有转换函数生成.xls需调整
Absolutely—you’ll need to tweak your function to output .xlsx instead of .xls, since these are two completely distinct file formats (.xls uses the old BIFF binary format, while .xlsx is based on open XML). The exact change depends on the library you’re using to generate the Excel file, so let’s walk through the most common tools:
Python (Pandas)
If you’re using pandas, the fix is straightforward:
- First, make sure you have the
openpyxlengine installed (it’s required for writing.xlsxfiles):pip install openpyxl - Modify your save call to specify the
.xlsxextension and (optionally) the engine for clarity:
Most recent pandas versions will auto-detect the correct engine based on the file extension, but explicitly setting it avoids issues with older versions.# Instead of df.to_excel("data.xls") df.to_excel("data.xlsx", engine="openpyxl")
JavaScript (SheetJS/XLSX Library)
For the popular SheetJS library, you just need to either:
- Use the
.xlsxfile extension in your output path, and the library will auto-set the correct format:XLSX.writeFile(workbook, "data.xlsx"); - Or explicitly specify the
bookTypeoption:XLSX.writeFile(workbook, "data.xlsx", { bookType: "xlsx" });
Java (Apache POI)
If you’re using Apache POI, you’ll need to switch from the old .xls-focused classes to the .xlsx equivalents:
- Replace
HSSFWorkbook(for.xls) withXSSFWorkbook(for.xlsx):// Old code for .xls // HSSFWorkbook workbook = new HSSFWorkbook(); // New code for .xlsx XSSFWorkbook workbook = new XSSFWorkbook(); - Save to a file with the
.xlsxextension:FileOutputStream outputStream = new FileOutputStream("data.xlsx"); workbook.write(outputStream); outputStream.close(); - Ensure you have the
poi-ooxmldependency added to your project (it’s separate from the core POI library).
Critical Note
Never just rename a .xls file to .xlsx manually—this will corrupt the file, as the internal structure of the two formats is entirely different. Always adjust your code to generate the correct format directly.
内容的提问来源于stack exchange,提问作者Pranav Kumar

