Excel to Json with uploaded file

Hi,

I want to upload xlsx file and use aspose.cells.net to covert it to json file.
For example, in this code,

	<html>
		<head>
			<title>Main</title>
			<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
			<script>
				function xlsxToJson() {
					var file = document.getElementById("fileDemo").files[0];
					if (!file) {
						return;
					}
					var formData = new FormData();
					formData.append('Upload', file);
					$.ajax({
						type: 'POST',
						url: "/Excel/Home/ExcelUpload",
						data: formData,
						processData: false,
						contentType: false,
						dataType: 'json',
						success: function (response) {
							console.log(response);
						},
						error: function (request, status, error) {
							console.log(request.responseText, status, error);
						}
					});

				}

			</script>
		</head>
		<body>
			<p><br /></p>
			<div class="container">
				<div class="title mb-2">
					<h3>Test Main</h3>
				</div>
				<div class="inputContainer">
					<input type="file" id="fileDemo" class="input" />
				</div>
				<input type="button" value="ToJson" onclick="xlsxToJson()" class="btn btn-primary m-2" />
			</div>
			<p><br /></p>
		</body>
	</html>

I want to send file to server, and use aspose.cells API like this (Convert-Excel-to-JSON|Documentation)
so I can use json file to save my DB, and load it to my view later. (maybe in that time, json → excel needed)

		[HttpPost]
		public String DownloadExcel(IFormFile Upload)
		{
			Workbook workbook = new Workbook(Upload);
		}

But (of course) it doesn’t work well.
can I change IFormFile to Aspose.Cells.FileFormatType ? or is there anything better way to use uploaded file?

@Shawnse

To convert an uploaded Excel file (XLSX) to JSON using Aspose.Cells in your ASP.NET application, you can follow these steps:

  1. File Upload: You already have a file upload mechanism in place using AJAX. This will send the uploaded file to your server.

  2. Handling the Uploaded File: In your server-side method, you need to read the uploaded file and convert it to JSON. You should not change IFormFile to Aspose.Cells.FileFormatType, as IFormFile is the correct type for handling file uploads in ASP.NET.

  3. Using Aspose.Cells to Convert to JSON: You can use the Workbook class from Aspose.Cells to load the uploaded file and then save it in JSON format. Here’s how you can implement this:

[HttpPost]
public IActionResult DownloadExcel(IFormFile Upload)
{
    if (Upload == null || Upload.Length == 0)
    {
        return BadRequest("No file uploaded.");
    }

    // Load the uploaded file into a Workbook
    using (var stream = new MemoryStream())
    {
        Upload.CopyTo(stream);
        var workbook = new Workbook(stream);

        // Save the workbook to JSON format
        var jsonFilePath = Path.Combine("path_to_save", "output.json");
        workbook.Save(jsonFilePath, SaveFormat.Json);

        return Ok(new { message = "File converted to JSON successfully.", jsonFilePath });
    }
}

Explanation:

  • File Upload Handling: The method checks if a file is uploaded. If not, it returns a bad request response.
  • MemoryStream: The uploaded file is copied to a MemoryStream, which is then used to create a Workbook instance.
  • Saving to JSON: The Save method of the Workbook class is called with SaveFormat.Json to save the workbook as a JSON file.

Additional Considerations:

  • Ensure that you have the necessary permissions to write to the directory where you are saving the JSON file.
  • You can customize the JSON output using JsonSaveOptions if needed, which allows you to specify additional settings for the export.

This approach will allow you to convert the uploaded Excel file to JSON format and use it as required in your application.

If you need further customization or have specific requirements for the JSON output, feel free to ask!

Sources:
[1]: Export Excel to JSON | Aspose.Cells Java Excel Processing API
[2]: Convert-Excel-to-JSON - Aspose Documentation

workbook.Save method is only helping to save json file…
can I use json String only for using it in code?

@Shawnse
You can do that. Instead of saving the JSON to a file with workbook.Save(), you can save it to a MemoryStream and then extract the JSON as a string

public IActionResult ConvertToJson(IFormFile Upload)
{
    if (Upload == null || Upload.Length == 0)
    {
        return BadRequest("No file uploaded.");
    }

    // Load the uploaded file into a Workbook
    using (var stream = new MemoryStream())
    {
        Upload.CopyTo(stream);
        var workbook = new Workbook(stream);

        // Use a MemoryStream to convert the workbook to JSON format
        using (var jsonStream = new MemoryStream())
        {
            workbook.Save(jsonStream, SaveFormat.Json);
            jsonStream.Seek(0, SeekOrigin.Begin); // Reset the stream position to ensure reading from the beginning

            // Read the JSON content from the MemoryStream
            using (var reader = new StreamReader(jsonStream))
            {
                var jsonContent = reader.ReadToEnd();
                
                // Here, you can directly use the jsonContent string, for example, returning it as a response
                return Ok(new { message = "File converted to JSON successfully.", jsonContent });
            }
        }
    }
}

Hope helps a bit!

Thank you. It helped me.
just one more question, could Aspose.Cells save excel to json with whole sheet’s style?

@Shawnse
Sorry, we currently do not support saving Excel to JSON with the whole sheet’s style.
We will analyze whether it can be supported, and if there are any plans to support it, we will notify you here.

1 Like

@Shawnse
Did you mean that you want to convert cells as Cell.ToJson() ?

I meant Convert-Excel-to-JSON|Documentation this function

@Shawnse
Now workbook.save(,SaveFormat.Json) only converts all value of workbook to json file. Could you please create an expected sample json with the whole sheet’s style? We will check it soon.