Json文件轉Excel


先創建一個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

 

以上為樓主總結,如有更好的方法請留言推薦,謝謝!

*:如需轉發請標注來源,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM