1.前端传入Json字符串,需要将前端传过来的json装成DataTable
源码如下:
public FileContentResult ExportToExcel(string tableData) {
DataTable table = new DataTable();
var array = JsonConvert.DeserializeObject(tableData) as JArray;//转换前端传进来json字符串
if (array.Count > 0)
{
StringBuilder columns = new StringBuilder();
JObject objColumns = array[0] as JObject;
//构造表头
foreach (JToken jkon in objColumns.AsEnumerable())
{
string name = ((JProperty)(jkon)).Name;
columns.Append(name + “,”);
table.Columns.Add(name);
}
//向表中添加数据
for (int i = 0; i < array.Count; i++)
{
DataRow row = table.NewRow();
JObject obj = array[i] as JObject;
foreach (JToken jkon in obj.AsEnumerable())
{
string name = ((JProperty)(jkon)).Name;
string value = ((JProperty)(jkon)).Value.ToString();
row[name] = value;
}
table.Rows.Add(row);
}
}
}
C# 导出excel (json转换为DataTable)
最新推荐文章于 2024-09-10 16:29:52 发布