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<List<ExportFieldParam>>(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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章