C#导出json数据到Excel表格

将接收到的data转为excel保存到桌面

public ActionResult ExportExcel()
{
     try
     {
         string json = Request.Params["data"];
         DataTable dt = JsonToDataTable(json);
         string excelname = System.DateTime.Now.ToString("yyyyMMddhhmmss");
         List<ExportFieldParam> columns = new List<ExportFieldParam>();
         if (dt.Columns.Contains("噪音数据")) {
             columns.Add(new ExportFieldParam("传感器", "传感器", 300));
             columns.Add(new ExportFieldParam("时间", "时间", 150));
             columns.Add(new ExportFieldParam("值", "值", 40));
             columns.Add(new ExportFieldParam("单位", "单位", 40));
             columns.Add(new ExportFieldParam("噪音数据", "噪音数据", 60));
         }
         else
         {
             columns.Add(new ExportFieldParam("传感器", "传感器", 300));
             columns.Add(new ExportFieldParam("时间", "时间", 300));
             columns.Add(new ExportFieldParam("值", "值", 40));
             columns.Add(new ExportFieldParam("单位", "单位", 40));
         }
         
         string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + excelname + ".xls";
         MemoryStream ms = RenderDataTableToExcel(dt, columns) as MemoryStream;
         
         FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
         byte[] data = ms.ToArray();
         fs.Write(data, 0, data.Length);
         fs.Flush();
         fs.Close();
         data = null;
         ms = null;
         fs = null;
         return File(filePath, "Application/excel", excelname + ".xls");
     }
     catch (Exception ex)
     {
         Console.WriteLine("ExportExcel错误,Exception:" + ex.Message);
     }

     return HttpNotFound();
 }
public static DataTable JsonToDataTable(string strJson)
{
    //转换json格式
    strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
    //取出表名   
    var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
    string strName = rg.Match(strJson).Value;
    DataTable tb = null;
    //去除表名   
    strJson = strJson.Substring(strJson.IndexOf("[") + 1);
    strJson = strJson.Substring(0, strJson.IndexOf("]"));

    //获取数据   
    rg = new Regex(@"(?<={)[^}]+(?=})");
    MatchCollection mc = rg.Matches(strJson);
    for (int i = 0; i < mc.Count; i++)
    {
        string strRow = mc[i].Value;
        string[] strRows = strRow.Split('*');

        //创建表   
        if (tb == null)
        {
            tb = new DataTable();
            tb.TableName = strName;
            foreach (string str in strRows)
            {
                var dc = new DataColumn();
                string[] strCell = str.Split('#');

                if (strCell[0].Substring(0, 1) == "\"")
                {
                    int a = strCell[0].Length;
                    dc.ColumnName = strCell[0].Substring(1, a - 2);
                }
                else
                {
                    dc.ColumnName = strCell[0];
                }
                tb.Columns.Add(dc);
            }
            tb.AcceptChanges();
        }

        //增加内容   
        DataRow dr = tb.NewRow();
        for (int r = 0; r < strRows.Length; r++)
        {
            try
            {
                string a = strRows[r].Split('#')[1].Trim();
                if (a.Equals("null"))
                {
                    dr[r] = "";
                }
                else
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
                }
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        tb.Rows.Add(dr);
        tb.AcceptChanges();
    }

    try
    {
        if (tb != null)
        {
            return tb;
        }
        else
        {
            throw new Exception("解析错误");
        }
    }
    catch (Exception e)
    {

        throw e;
    }
}
protected Stream RenderDataTableToExcel(DataTable SourceTable, List<ExportFieldParam> columns)
{
    // JavaScriptSerializer serializer = new JavaScriptSerializer();
    // var columns = serializer.Deserialize>(columnstr);



    MemoryStream ms = new MemoryStream();
    NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
    NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
    NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
    int columnIndex = 0;

    for (int i = 0; i < columns.Count; i++)
    {
        String title = columns[i].title;
        int width = columns[i].width;
        sheet.SetColumnWidth(columnIndex, width * 40);
        headerRow.CreateCell(columnIndex).SetCellValue(title);
        columnIndex++;
    }

    for (int rowIndex = 0; rowIndex < SourceTable.Rows.Count && rowIndex < 65535; rowIndex++)
    {
        NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex + 1);//第一行是列名
        //dataRow.Height = (int)((100) * 17);
        columnIndex = 0;
        for (int i = 0; i < columns.Count; i++)
        {
            String field = columns[i].field;
            String cellValue;
            if (SourceTable.Rows[rowIndex][field].GetType().FullName == "System.DateTime")
            {
                System.DateTime myDateTime = (System.DateTime)SourceTable.Rows[rowIndex][field];
                cellValue = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                cellValue = SourceTable.Rows[rowIndex][field].ToString();
            }
            dataRow.CreateCell(columnIndex).SetCellValue(cellValue);
            columnIndex++;
        }
    }
    workbook.Write(ms);
    ms.Flush();
    ms.Position = 0;
    sheet = null;
    headerRow = null;
    workbook = null;
    return ms;
}

你可能感兴趣的:(C#)