Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Last active February 7, 2022 01:32
Code to convert JSON to Excel in Java. Have a look at this article for further details: https://kb.aspose.com/cells/java/how-to-convert-json-to-excel-in-java/
import java.nio.file.Files;
import java.nio.file.Paths;
import com.aspose.cells.CellsFactory;
import com.aspose.cells.Color;
import com.aspose.cells.JsonLayoutOptions;
import com.aspose.cells.JsonUtility;
import com.aspose.cells.License;
import com.aspose.cells.Style;
import com.aspose.cells.TextAlignmentType;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
public class ConvertJsonToExcelInJava {
public static void main(String[] args) throws Exception { //main function for ConvertJsonToExcelInJava class to convert JSON to Excel in Java
// Use Aspose.Cells license to remove watermark in the output Excel file generated from JSON data
License licenseForJsonToXlsx = new License();
licenseForJsonToXlsx.setLicense("Aspose.Cells.lic");
// Create a new workbook that will be used to save JSON data in Excel
Workbook wbToSaveJson = new Workbook();
// Get the target worksheet reference in the loaded workbook
Worksheet worksheetRef = wbToSaveJson.getWorksheets().get(0);
// Load the JSON data into a string variable from the source JSON file
String jsonString = new String(Files.readAllBytes(Paths.get("SampleJsonData.json")));
// Instantiate the style object for formatting the JSON data in output Excel
CellsFactory asposeCellsFactory = new CellsFactory();
Style styleForTitle = asposeCellsFactory.createStyle();
styleForTitle.setHorizontalAlignment(TextAlignmentType.CENTER);
styleForTitle.getFont().setColor(Color.getBlueViolet());
styleForTitle.getFont().setBold(true);
// Create the JsonLayoutOptions class object to format data while calling importData() function
JsonLayoutOptions jsonLayoutOptions = new JsonLayoutOptions();
jsonLayoutOptions.setTitleStyle(styleForTitle);
jsonLayoutOptions.setArrayAsTable(true);
// Use the importData() function by providing required parameters
JsonUtility.importData(jsonString, worksheetRef.getCells(), 3, 5, jsonLayoutOptions);
// Save the resultant workbook containing the JSON data
wbToSaveJson.save("OutputXlsx.xlsx");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment