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

2020-08-04 06:27发布

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 - enter image description here

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' });

标签: c# json excel
2条回答
该账号已被封号
2楼-- · 2020-08-04 07:10

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.

查看更多
时光不老,我们不散
3楼-- · 2020-08-04 07:13

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.
查看更多
登录 后发表回答