c# 导出

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using ADOX;
using System.Collections;
using System.Text.RegularExpressions;

namespace Db.RWM.Data
{
    
    public class DbRWMData
    {
        
        /// <summary>
        /// 将Excel 上传到服务器 ***时间 2016-08-13 ****
        /// </summary>
        /// <param name="PostFile">从客户端接受的 Request.Files["excel"]</param>
        /// <param name="ServerSaveUrl">保存在服务器中的路径</param>
        /// <returns>bool</returns>
        public bool WebUpLoadExcel(HttpPostedFile PostFile,string ServerSaveUrl)
        {
            string fileType = Path.GetExtension(PostFile.FileName);
            if (fileType == ".xls" || fileType == ".xlsx")
            {
                
                if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(ServerSaveUrl)))
                {
                    File.Delete(System.Web.HttpContext.Current.Server.MapPath(ServerSaveUrl));
                }
                //保存到服务器
                PostFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(ServerSaveUrl));
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 读取改路径下的Excel ,转换成DataSet返回,并删除Excel *** 时间 2016-08-13 ****
        /// </summary>
        /// <param name="filePath">Excel路径</param>
        /// <returns>DataSet</returns>
        public DataSet WebGetDataSetFromServerExcel(string filePath)
        {
            string connStr = "";

            //文件名称
            string FileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

            string fileType = System.IO.Path.GetExtension(FileName);
            if (string.IsNullOrEmpty(fileType)) return null;

            if (fileType == ".xls")
                connStr = "Provider=Microsoft.Jet.OLEDB.4.0; " + " Data Source=" + filePath + " ; Extended Properties=Excel 8.0";
            else
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + " ; Extended Properties=Excel 12.0";

            OleDbConnection conn = null;
            OleDbDataAdapter da = null;
            DataTable dtSheetName = null;

            DataSet ds = new DataSet();
            // 初始化连接,并打开
            conn = new OleDbConnection(connStr);
            conn.Open();

            // 获取数据源的表定义元数据                        
            dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            string tableName = dtSheetName.Rows[0][2].ToString().Trim();
            // 初始化适配器
            string sSql = " Select *  FROM  [" + tableName + "]  ";


            da = new OleDbDataAdapter(sSql, conn);

            DataSet aa = new DataSet();

            da.Fill(aa, tableName);
            conn.Close();
            //删除服务器里上传的文件  
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            return aa;
        }

        /// <summary>
        /// Web端将DataSet导出到Excel中   *** 时间 2016-08-13 ****
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public bool WebExportDataSetToExcel(DataSet ds,int BanBen)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true; 
            // HttpContext.Current.Response.Charset = "UTF-8";
            if (BanBen == 1)
            {
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename= cus" + DateTime.Now + ".xls");
            }
            else
            {
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename= cus" + DateTime.Now + ".xlsx");
            }
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            if (ds != null)
            {
                System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid();
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    dataGrid.DataSource = ds.Tables[i].DefaultView;
                    dataGrid.DataBind();
                    dataGrid.RenderControl(oHtmlTextWriter);
                }
                
            }
            StringBuilder sN = new StringBuilder();
            sN.Append(AddExcelHead());
            sN.Append(oStringWriter.ToString());
            sN.Append(AddExcelbottom());
            HttpContext.Current.Response.Output.Write(sN.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
            return true;
        }

        /// <summary>
        /// Web端将DataSet导出到Excel中   *** 时间 2016-08-13 ****
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public bool WebExportDataSetToExcel(System.Data.DataTable dtData, TableCell[] header, string fileName, Dictionary<int, int> mergeCellNums, int? mergeKey)
        {
            System.Web.UI.WebControls.GridView gvExport = null;
            // 当前对话 
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件 
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式 
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                curContext.Response.Charset = "gb2312";
                if (!string.IsNullOrEmpty(fileName))
                {
                    //处理中文名乱码问题
                    fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                    curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + (fileName.ToLower().EndsWith(".xls") ? fileName : fileName + ".xls")));
                }
                // 导出excel文件 
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 重新定义一个无分页的GridView 
                gvExport = new System.Web.UI.WebControls.GridView();
                gvExport.DataSource = dtData.DefaultView;
                gvExport.AllowPaging = false;
                //优化导出数据显示,如身份证、12-1等显示异常问题
                gvExport.RowDataBound += new System.Web.UI.WebControls.GridViewRowEventHandler(dgExport_RowDataBound);

                gvExport.DataBind();
                //处理表头
                if (header != null && header.Length > 0)
                {
                    gvExport.HeaderRow.Cells.Clear();
                    gvExport.HeaderRow.Cells.AddRange(header);
                }
                //合并单元格
                if (mergeCellNums != null && mergeCellNums.Count > 0)
                {
                    foreach (int cellNum in mergeCellNums.Keys)
                    {
                        MergeRows(gvExport, cellNum, mergeCellNums[cellNum], mergeKey);
                    }
                }

                // 返回客户端 
                gvExport.RenderControl(htmlWriter);
                curContext.Response.Clear();
                curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString());
                curContext.Response.End();

                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 描述:行绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected  void dgExport_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    //优化导出数据显示,如身份证、12-1等显示异常问题
                    if (Regex.IsMatch(cell.Text.Trim(), @"^\d{12,}$") || Regex.IsMatch(cell.Text.Trim(), @"^\d+[-]\d+$"))
                    {
                        cell.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                    }
                }
            }
        }

        public  void MergeRows(GridView gvExport, int cellNum, int mergeMode, int? mergeKey)
        {
            int i = 0, rowSpanNum = 1;
            System.Drawing.Color alterColor = System.Drawing.Color.LightGray;
            while (i < gvExport.Rows.Count - 1)
            {
                GridViewRow gvr = gvExport.Rows[i];
                for (++i; i < gvExport.Rows.Count; i++)
                {
                    GridViewRow gvrNext = gvExport.Rows[i];
                    if ((!mergeKey.HasValue || (mergeKey.HasValue && (gvr.Cells[mergeKey.Value].Text.Equals(gvrNext.Cells[mergeKey.Value].Text) || "&nbsp;".Equals(gvrNext.Cells[mergeKey.Value].Text)))) && ((mergeMode == 1 && gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text) || (mergeMode == 2 && "&nbsp;".Equals(gvrNext.Cells[cellNum].Text.Trim())) || (mergeMode == 3 && (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text || "&nbsp;".Equals(gvrNext.Cells[cellNum].Text.Trim())))))
                    {
                        gvrNext.Cells[cellNum].Visible = false;
                        rowSpanNum++;
                        gvrNext.BackColor = gvr.BackColor;
                    }
                    else
                    {
                        gvr.Cells[cellNum].RowSpan = rowSpanNum;
                        rowSpanNum = 1;
                        //间隔行加底色,便于阅读
                        if (mergeKey.HasValue && cellNum == mergeKey.Value)
                        {
                            if (alterColor == System.Drawing.Color.White)
                            {
                                gvr.BackColor = System.Drawing.Color.LightGray;
                                alterColor = System.Drawing.Color.LightGray;
                            }
                            else
                            {
                                alterColor = System.Drawing.Color.White;
                            }
                        }
                        break;
                    }
                    if (i == gvExport.Rows.Count - 1)
                    {
                        gvr.Cells[cellNum].RowSpan = rowSpanNum;
                        if (mergeKey.HasValue && cellNum == mergeKey.Value)
                        {
                            if (alterColor == System.Drawing.Color.White)
                                gvr.BackColor = System.Drawing.Color.LightGray;
                        }
                    }
                }
            }
        }

        public DataTable Not_Import_Excel(string filePath, bool Is03)
        {
            string sqlconn = "";
            if (Is03)
            {
                sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
            }
            else
            {
                sqlconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=False;IMEX=1'";
            }

            string sql = @"select * from [Sheet1$]";

            try
            {
                using (OleDbConnection conn = new OleDbConnection(sqlconn))
                {
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn))
                    {
                        System.Data.DataTable dt = new System.Data.DataTable();
                        adapter.Fill(dt);

                        return dt;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开文件出错,错误信息:" + ex.Message.ToString(), "提示");
                return null;
            }

        }


        public  string AddExcelHead()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");

            sb.Append(" <head>");

            sb.Append(" <!--[if gte mso 9]><xml>");

            sb.Append("<x:ExcelWorkbook>");

            sb.Append("<x:ExcelWorksheets>");

            sb.Append("<x:ExcelWorksheet>");

            sb.Append("<x:Name></x:Name>");

            sb.Append("<x:WorksheetOptions>");

            sb.Append("<x:Print>");

            sb.Append("<x:ValidPrinterInfo />");

            sb.Append(" </x:Print>");

            sb.Append("</x:WorksheetOptions>");

            sb.Append("</x:ExcelWorksheet>");

            sb.Append("</x:ExcelWorksheets>");

            sb.Append("</x:ExcelWorkbook>");

            sb.Append("</xml>");

            sb.Append("<![endif]-->");

            sb.Append(" </head>");

            sb.Append("<body>");

            return sb.ToString();



        }
        /// <summary>

        /// Excel尾部

        /// </summary>

        /// <returns></returns>

        public  string AddExcelbottom()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append("</body>");

            sb.Append("</html>");

            return sb.ToString();

        }

        /// <summary>
        /// 单机版的将DataGridView中的数据导出到Excel  *** 时间 2016-08-13 ****
        /// </summary>
        /// <param name="SaveFileName">导出的文件名称</param>
        /// <param name="m_DataView">DataGridView控件名称</param>
        public void NotWebExportDataToExcel(string SaveFileName, DataGridView m_DataView)
        {
            SaveFileDialog kk = new SaveFileDialog();
            kk.Title = "保存EXECL文件";
            kk.Filter = "EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*";

            kk.FileName = SaveFileName;
            kk.FilterIndex = 1;
            if (kk.ShowDialog() == DialogResult.OK)
            {
                string FileName = kk.FileName;
                if (File.Exists(FileName))
                    File.Delete(FileName);
                FileStream objFileStream;
                StreamWriter objStreamWriter;
                string strLine = "";
                objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
                for (int i = 0; i < m_DataView.Columns.Count; i++)
                {
                    if (m_DataView.Columns[i].Visible == true)
                    {
                        strLine = strLine + m_DataView.Columns[i].HeaderText.ToString() + Convert.ToChar(9);
                    }
                }
                objStreamWriter.WriteLine(strLine);
                strLine = "";

                for (int i = 0; i < m_DataView.Rows.Count; i++)
                {
                    if (m_DataView.Columns[0].Visible == true)
                    {
                        if (m_DataView.Rows[i].Cells[0].Value == null)
                            strLine = strLine + " " + Convert.ToChar(9);
                        else
                            strLine = strLine + " " + m_DataView.Rows[i].Cells[0].Value.ToString() + Convert.ToChar(9);
                    }
                    for (int j = 1; j < m_DataView.Columns.Count; j++)
                    {
                        if (m_DataView.Columns[j].Visible == true)
                        {
                            if (m_DataView.Rows[i].Cells[j].Value == null)
                                strLine = strLine + " " + Convert.ToChar(9);
                            else
                            {
                                string rowstr = "";
                                rowstr = m_DataView.Rows[i].Cells[j].Value.ToString();
                                if (rowstr.IndexOf("\r\n") > 0)
                                    rowstr = rowstr.Replace("\r\n", " ");
                                if (rowstr.IndexOf("\t") > 0)
                                    rowstr = rowstr.Replace("\t", " ");

                                if (j == 12)
                                {
                                    if (rowstr.Length > 1)
                                    {
                                        rowstr = rowstr.Insert(rowstr.Length - 1, ".");
                                    }
                                }
                                if (j == 4 || j == 15)
                                {
                                    strLine = strLine + "" + rowstr + Convert.ToChar(9);
                                }
                                else
                                {
                                    strLine = strLine + rowstr + Convert.ToChar(9);
                                }
                            }
                        }
                    }
                    objStreamWriter.WriteLine(strLine);
                    strLine = "";
                }
                objStreamWriter.Close();
                objFileStream.Close();
                
            }
        }
        
        /// <summary>
        /// 在本地已经创建好的数据库中,创建表 *** 时间 2016-10-12 ***
        /// </summary>
        /// <param name="filePath">数据库路径</param>
        /// <param name="tableName">表名</param>
        /// <param name="m_DataView">字段GridView</param>
        /// <returns>Bool</returns>
        public bool CreateAccessDataTable(string filePath, string tableName, DataGridView m_DataView)
        {
            try
            {
                ADOX.Catalog catalog = new Catalog();
                string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + filePath;
                
                ADODB.Connection cn = new ADODB.Connection();
                cn.Open(ConnectionString, null, null, -1);
                catalog.ActiveConnection = cn;
                ADOX.Table table = new ADOX.Table();
                table.Name = tableName;//传递过来的表名
                //添加主键,并设置为自动编号
                
                ADOX.Column column = new ADOX.Column();

                column.ParentCatalog = catalog;

                for (int i = 0; i < m_DataView.Rows.Count; i++)
                {

                    if (m_DataView.Rows[i].Cells[0].Value != null)
                    {
                        switch (m_DataView.Rows[i].Cells[1].Value.ToString())
                        {
                            case "自动编号":
                                {
                                    column.Name = m_DataView.Rows[i].Cells[0].Value.ToString();
                                    column.Type = DataTypeEnum.adInteger;

                                    column.DefinedSize = 9;

                                    column.Properties["AutoIncrement"].Value = true;

                                    table.Columns.Append(column, DataTypeEnum.adInteger, 9);

                                    table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null);
                                    break;
                                }
                            case "数字":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adInteger, 9);
                                    break;
                                }
                            case "备注":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adLongVarChar, 200);
                                    break;
                                }
                            case "文本":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adVarWChar, 50);
                                    break;
                                }
                            case "时间":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adDate, 0);
                                    break;
                                }
                            case "货币":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adCurrency, 18);
                                    break;
                                }
                            case "是/否":
                                {
                                    table.Columns.Append(m_DataView.Rows[i].Cells[0].Value.ToString(), DataTypeEnum.adBoolean, 1);
                                    break;
                                }
                            default:
                                break;
                        }
                    }
                }

                catalog.Tables.Append(table);

                cn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }


        /// <summary>
        /// 获取数据库中的所有表名
        /// </summary>
        /// <param name="filePath">数据库路径</param>
        /// <returns></returns>
        public DataTable GetAllDataBaseTableName(string filePath)
        {
            //C#获取Access数据库中的所有表名
            if (string.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("没有路径");
                return null;
            }
            string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + filePath;
            OleDbConnection Conn = new OleDbConnection(ConnectionString);
            try
            {
                Conn.Open();
                DataTable shemaTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                shemaTable.Columns.Remove("table_catalog");
                shemaTable.Columns.Remove("table_schema");
                shemaTable.Columns.Remove("table_type");
                shemaTable.Columns.Remove("table_guid");
                shemaTable.Columns.Remove("description");
                shemaTable.Columns.Remove("table_propid");
                shemaTable.Columns.Remove("date_created");
                shemaTable.Columns.Remove("date_modified");
                return shemaTable;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Conn.Close();
            }
        }

        /// <summary>
        /// 判断在该数据库下是否存在该表
        /// </summary>
        /// <param name="filePath">数据库的路径</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public bool IsExistTableName(string filePath,string tableName)
        {
            OleDbCommand myCommand = new OleDbCommand();
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath;
            OleDbConnection myConnection = new OleDbConnection();
            string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(filePath);
            myCommand.CommandText = "SELECT COUNT(*) FROM " + fileNameWithoutExtension + " where type='u' and name='" + tableName + "'";
            myConnection.ConnectionString = strCon;
            myCommand.Connection = myConnection;
            myConnection.Open();
            if (myCommand.ExecuteNonQuery() == 0)
            {
                return false;
            }else{return true;}
        }

        /// <summary>
        /// 更具表名,获取表中的属性和字段名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public DataTable GetFileNameAndProPerTies(string filePath, string tableName)
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath;
            OleDbConnection myConnection = new OleDbConnection();
            myConnection.ConnectionString = strCon;
            try
            {
                DataTable table = new DataTable();
                myConnection.Open();
                DataSet MyDataSet = new DataSet();
                OleDbDataAdapter MyAdapter = new OleDbDataAdapter("select * from " + tableName, myConnection);
                MyAdapter.Fill(MyDataSet);
                table = MyDataSet.Tables[0];
                return table;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
            finally
            {
                myConnection.Close();
            }
        }

        /// <summary>
        /// 获取表名下的所有字段
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="filePath">数据库路径</param>
        /// <returns></returns>
        public DataTable GetTableFileName(string TableName, string filePath)
        {
            string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + filePath;
            OleDbConnection Conn = new OleDbConnection(ConnectionString);
            Conn.Open();
            try
            {
                DataTable columnTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null });
                if (columnTable.Rows.Count > 0)
                {
                    for (int i = columnTable.Columns.Count - 1; i >= 0; i--)
                    {
                        if (i == 3) { continue; }
                        columnTable.Columns.RemoveAt(i);
                    }
                    return columnTable;
                }
                else
                { return null; }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return null;
            }
            finally
            {
                Conn.Close();
            }
        }


        /// <summary>
        /// 在服务器中的数据库中,创建表
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="Path">数据库路径</param>
        /// <returns></returns>
        public bool CreatSqlDataTable(string TableName,string Path,DataGridView fileDataGridView)
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Path;
            string strTableName = TableName;
            OleDbCommand myCommand = new OleDbCommand();
            OleDbConnection myConnection = new OleDbConnection();
            OleDbDataAdapter myAdapter = new OleDbDataAdapter();
            DataSet myDataSet = new DataSet();


            DataTable dtCurrent = new DataTable();
            int nr = dtCurrent.Rows.Count;
            int nc = dtCurrent.Columns.Count;
            string StrCmd = "CREATE TABLE " + TableName + "(";
            for (int i = 0; i < fileDataGridView.Rows.Count; i++)
            {
                switch (fileDataGridView.Rows[i].Cells[1].ToString())
                {
                    case "自动编号": { break; }
                    case "数字": { break; }
                    case "备注": { break; }
                    case "是/否": { break; }
                    case "时间": { break; }
                    case "文本": { break; }
                    case "货币": { break; }
                    default:
                        break;
                }
            }
            myConnection.ConnectionString = strCon;
            myCommand.Connection = myConnection;
            myCommand.CommandText = StrCmd;
            myConnection.Open();
            myCommand.ExecuteNonQuery();
            return true;
        }


        #region Json 字符串 转换为 DataTable数据集合
    /// <summary>
    /// Json 字符串 转换为 DataTable数据集合
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    public  DataTable ToDataTable(string json)
    {
        DataTable dataTable = new DataTable();  //实例化
        DataTable result;
        try
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
            if (arrayList.Count > 0)
            {
                foreach (Dictionary<string, object> dictionary in arrayList)
                {
                    if (dictionary.Keys.Count == 0)
                    {
                        result = dataTable;
                        return result;
                    }
                    if (dataTable.Columns.Count == 0)
                    {
                        foreach (string current in dictionary.Keys)
                        {
                            dataTable.Columns.Add(current, dictionary[current].GetType());
                        }
                    }
                    DataRow dataRow = dataTable.NewRow();
                    foreach (string current in dictionary.Keys)
                    {
                        dataRow[current] = dictionary[current];
                    }
 
                    dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                }
            }
        }
        catch
        {
        }
        result = dataTable;
        return result;
    }
    #endregion

         #region DataTable 转换为Json 字符串
    /// <summary>
    /// DataTable 对象 转换为Json 字符串
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string ToJson(DataTable dt)
    {
        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
        ArrayList arrayList = new ArrayList();
        foreach (DataRow dataRow in dt.Rows)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
            foreach (DataColumn dataColumn in dt.Columns)
            {
                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
            }
            arrayList.Add(dictionary); //ArrayList集合中添加键值
        }
 
        return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
    }
    #endregion
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值