简体   繁体   中英

How to create excel file using json data using c#?

I have sample json data and want to create a xls file using that.

"{\"Id\":\"123\",\"Name\":\"DEMO\",\"Address\":\"US\",\"Team\":\"JK\"}"

Want to create a excel file stream which I will upload on azure storage using below code -

CloudFile cloudFile = cloudFileDirectory.GetFileReference("filename.xls");
cloudFile.UploadFromStream(fileStream);

output expected - 在此处输入图片说明

I'm able to create csv by below code -

var result = new StringBuilder();
    for (int i = 0; i < table.Columns.Count; i++)
    {
        result.Append(table.Columns[i].ColumnName);
        result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
    }
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(row[i].ToString());
            result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
        }
    }
    return result.ToString().TrimEnd(new char[] { '\r', '\n' });

to generate xls file from json files you should done those steps

  1. Read file
  2. Parse JSON file ( Json.NET is the best) to your c# Class object.
  3. Choose xls framework(using Open XML SDK or anyone which do you find)
  4. Use structure from step 2 to fill columns and rows in xls file using framework API from step 3.

If you already have a datatable, then you can convert a data table to a spreadsheet as easy as pie using EPPLus. The code could be as simple as this:

FileInfo f = new FileInfo("filename.xlsx");
ExcelPackage package = new ExcelPackage(f);

ExcelWorksheet ws = package.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(table, true);

If you have some special handling, for date formats and such, it might be moderately more work, but not much.

From Nuget:

Install-Package EPPlus

If you've ever worked with Excel Interop, you will love how much easier EPPlus is to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM