简体   繁体   English

如何使用C#使用JSON数据创建Excel文件?

[英]How to create excel file using json data using c#?

I have sample json data and want to create a xls file using that. 我有示例json数据,并希望使用该数据创建一个xls文件。

"{\"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 - 想要创建一个Excel文件流,我将使用以下代码将其上传到Azure存储中-

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

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

I'm able to create csv by below code - 我可以通过以下代码创建csv-

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 从json文件生成xls文件,您应该执行以下步骤

  1. Read file 读取档案
  2. Parse JSON file ( Json.NET is the best) to your c# Class object. 将JSON文件(最好是Json.NET )解析为c#Class对象。
  3. Choose xls framework(using Open XML SDK or anyone which do you find) 选择xls框架(使用Open XML SDK或您发现的任何人)
  4. Use structure from step 2 to fill columns and rows in xls file using framework API from step 3. 使用步骤2中的结构,并使用步骤3中的框架API填充xls文件中的列和行。

If you already have a datatable, then you can convert a data table to a spreadsheet as easy as pie using EPPLus. 如果您已有数据表,则可以使用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: 从Nuget:

Install-Package EPPlus

If you've ever worked with Excel Interop, you will love how much easier EPPlus is to work with. 如果您曾经使用过Excel Interop,那么您会爱上EPPlus的使用变得多么容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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