Json文件转Excel

本文详细介绍如何在.NET环境下,通过读取根目录下的JSON文件并利用Newtonsoft库将数据转换为DataTable,进而转换为Dataset,最终导出为Excel文件的全过程。文章提供了完整的代码示例,包括如何处理文件路径、读取JSON数据、转换数据类型以及设置HTTP响应以实现文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建一个web项目,在根目录放置需要转换的json文件,直接读取静态Json文件加载数据进行转换,代码如下:

string Json = string.Empty;
            List<object> list = new List<object>();
            string filePath = Server.MapPath("/***.json");//指定目录下的json文件(当前为根目录)
            using (FileStream fs = new FileStream(filePath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312")))
                {
                    Json = sr.ReadToEnd().ToString();
                }
            }
View Code

接着引入Newtonsoft.Json 文件,将Json字符串转Datatable

 DataTable dt = (DataTable)JsonConvert.DeserializeObject(Json, typeof(DataTable));

然后将Datable转成Dataset

DataSet ds = new DataSet();
ds.Tables.Add(dt);

最后直接用Response导出结果:

ExportResult(ds, "Json.xls");//Json.xls名字自定义

用到的ExportResult方法代码如下:

/// <summary>
        /// 将ds转换成excel
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="excelName"></param>
        public void ExportResult(DataSet ds, string excelName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            DataGrid dg = new DataGrid();
            dg.DataSource = ds;
            dg.DataBind();
            dg.RenderControl(htmlWrite);
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelName));
            HttpContext.Current.Response.Write(stringWrite.ToString());
            HttpContext.Current.Response.End();
        }
View Code

 

以上为楼主总结,如有更好的方法请留言推荐,谢谢!

*:如需转发请标注来源,谢谢!

转载于:https://www.cnblogs.com/HenryWEI/p/9804679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值