Articles in this section
Category / Section

How to convert CSV document with JSON data to XLSX using C# in ASP.NET Core?

5 mins read

Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. Also, converts Excel documents to PDF files.

Using Syncfusion, we can convert CSV to Excel document. In this article, we will explore how to convert CSV document with JSON data to Excel document.

Steps for converting CSV with JSON data to Excel programmatically:

Step 1: Create a new C# console application project.

Create a new C# console application.png

Step 2: Install the Syncfusion.XlsIO.Net.Core NuGet package as reference to your .NET Core applications from NuGet.org.

Install Syncfusion XlsIO Net Core nuget package.png

Step 3: Include the following namespaces in Program.cs file.

C#

using Syncfusion.XlsIO; 

Step 4: Include the following code snippet to convert CSV with JSON data to Excel document.

C#

bool startConcatenation = false;
string startCellAddress = "";
List<string> concatenatedValues = new List<string>();

using (ExcelEngine excelEngine = new ExcelEngine())
{
   IApplication application = excelEngine.Excel;
   application.DefaultVersion = ExcelVersion.Xlsx;

   //Loads an CSV file
   FileStream fileStream = new FileStream(@"../../../Data/InputTemplate.csv", FileMode.Open, FileAccess.Read);
   IWorkbook workbook = application.Workbooks.Open(fileStream, ";");
   IWorksheet worksheet = workbook.Worksheets[0];

   for (int row = 1; row <= worksheet.UsedRange.LastRow; row++)
   {
       for (int col = 1; col <= worksheet.UsedRange.LastColumn; col++)
       {
           IRange cell = worksheet.UsedRange[row, col];
           string cellValue = cell.DisplayText;

           //Checks the cellvalue starts with {
           if (cellValue.StartsWith("\"{\n") || cellValue.StartsWith(" \"{"))
           {
               startConcatenation = true;
               startCellAddress = cell.AddressLocal;
               concatenatedValues.Add(cellValue);
               continue; //Skip to the next cell
           }

           //Concatenate the JSON value to the list
           if (startConcatenation && !string.IsNullOrEmpty(cellValue))
           {
               
               concatenatedValues.Add(cellValue);
               cell.Clear();
           }

           //Update the JSON value in the respective cell
           if (cellValue.Contains("}\""))
           {
               startConcatenation = false;
               //Concatenate the values 
               string concatenatedValue = string.Join(" ", concatenatedValues);

               //Update the corresponding cell with the concatenated value
               worksheet.Range[startCellAddress].Value = concatenatedValue;

               //Clear the list for the next iteration
               concatenatedValues.Clear();

               //Reset the start cell address for the next iteration
               startCellAddress = "";
           }
       }
   }

   //Check for blank row
   List<int> rowsToDelete = new List<int>();
   for (int row = 1; row <= worksheet.UsedRange.LastRow; row++)
   {
       bool isRowEmpty = true;
       for (int col = 1; col <= worksheet.UsedRange.LastColumn; col++)
       {
           IRange cell = worksheet.Range[row, col];
           if (!string.IsNullOrEmpty(cell.Value))
           {
               isRowEmpty = false;
               break;
           }
       }
       if (isRowEmpty)
       {
           rowsToDelete.Add(row);
       }
   }

   //Delete the blank rows
   for (int i = 0; i < rowsToDelete.Count; i++)
   {
       worksheet.DeleteRow(rowsToDelete[i] - i);
   }

   worksheet.UsedRange.WrapText = false;
   worksheet.UsedRange.AutofitColumns();
   FileStream outputStream = new FileStream("output.xlsx", FileMode.Create, FileAccess.Write);
   workbook.SaveAs(outputStream);
} 

A complete working sample of how to convert CSV with JSON to Excel using C# can be downloaded from here.

Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheets or workbooks, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to a worksheet using Template Markers, and most importantly PDF and Image conversions with code examples.

Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features.

Conclusion

I hope you enjoyed learning about how to convert CSV document with JSON data to XLSX using C#

You can refer to our ASP.NET Core XIsIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core XIsIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Note:
Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion license key in your application to use the components without a trial message.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied