合并查询结果

将数据导入exceL中,不想再C#里直接计算,直接将查询总数量合并 直接返回

SELECT e_salecode as b,count(e_quantity) as a
  FROM e_stockout where e_stockid in(3,4) and e_senddate='2012-01-12' group by e_salecode
union all select 'Total Count', count(e_quantity)
  FROM e_stockout where e_stockid in(3,4) and e_senddate='2012-01-12'


excel类 两种方式任选,第一种可直接导出另存为,第二种直接写入excel文件 必须指定好路径

 /// <summary>
    /// 导出Excel文件,并自定义文件名
    /// </summary>
    public  void Excel(System.Data.DataTable dtData, String FileName)
    {
        GridView dgExport = null;
        HttpContext curContext = HttpContext.Current;
        StringWriter strWriter = null;
        HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
          //  curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
          //  curContext.Response.ContentType = "application nd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //curContext.Response.Charset = "UTF8";
            curContext.Response.Clear();

            //byte[] preamble = System.Text.Encoding.UTF8.GetPreamble();
            //curContext.Response.Write(preamble);

            curContext.Response.ContentType = "application/octet-stream";
            strWriter = new StringWriter();
            htmlWriter = new HtmlTextWriter(strWriter);
          
            dgExport = new GridView();
            dgExport.DataSource = dtData.DefaultView;
            dgExport.AllowPaging = false;
            dgExport.DataBind();
          
            int sum = 0;
            if (dtData.Rows.Count > 0)
            {
                dgExport.RenderControl(htmlWriter);
              
            }
            curContext.Response.Write(strWriter.ToString());
        
           curContext.Response.End();
          
        }
    }

    /// <summary>
    /// 将数据导出至Excel文件
    /// </summary>
    /// <param name="Table">DataTable对象</param>
    /// <param name="ExcelFilePath">Excel文件路径</param>
    public  bool OutputToExcel(DataTable Table, string ExcelFilePath)
    {
        if (File.Exists(ExcelFilePath))
        {
            throw new Exception("该文件已经存在!");
        }

        if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
        {
            Table.TableName = "Sheet1";
        }

        //数据表的列数
        int ColCount = Table.Columns.Count;

        //用于记数,实例化参数时的序号
        int i = 0;

        //创建参数
        OleDbParameter[] para = new OleDbParameter[ColCount];

        //创建表结构的SQL语句
        string TableStructStr = @"Create Table " + Table.TableName + "(";

        //连接字符串
        string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
        OleDbConnection objConn = new OleDbConnection(connString);
       
        //创建表结构
        OleDbCommand objCmd = new OleDbCommand();

        //数据类型集合
        ArrayList DataTypeList = new ArrayList();
        DataTypeList.Add("System.Decimal");
        DataTypeList.Add("System.Double");
        DataTypeList.Add("System.Int16");
        DataTypeList.Add("System.Int32");
        DataTypeList.Add("System.Int64");
        DataTypeList.Add("System.Single");

        //遍历数据表的所有列,用于创建表结构
        foreach (DataColumn col in Table.Columns)
        {
            //如果列属于数字列,则设置该列的数据类型为double
            if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0)
            {
                para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double);
                objCmd.Parameters.Add(para[i]);

                //如果是最后一列
                if (i + 1 == ColCount)
                {
                    TableStructStr += col.ColumnName + " double)";
                }
                else
                {
                    TableStructStr += col.ColumnName + " double,";
                }
            }
            else
            {
                para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar);
                objCmd.Parameters.Add(para[i]);

                //如果是最后一列
                if (i + 1 == ColCount)
                {
                    TableStructStr += col.ColumnName + " varchar)";
                }
                else
                {
                    TableStructStr += col.ColumnName + " varchar,";
                }
            }
            i++;
        }

        //创建Excel文件及文件结构
        try
        {
            objCmd.Connection = objConn;
            objCmd.CommandText = TableStructStr;

            if (objConn.State == ConnectionState.Closed)
            {
                objConn.Open();
            }
            objCmd.ExecuteNonQuery();
        }
        catch (Exception exp)
        {
            throw exp;
        }

        //插入记录的SQL语句
        string InsertSql_1 = "Insert into " + Table.TableName + " (";
        string InsertSql_2 = " Values (";
        string InsertSql = "";

        //遍历所有列,用于插入记录,在此创建插入记录的SQL语句
        for (int colID = 0; colID < ColCount; colID++)
        {
            if (colID + 1 == ColCount)  //最后一列
            {
                InsertSql_1 += Table.Columns[colID].ColumnName + ")";
                InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")";
            }
            else
            {
                InsertSql_1 += Table.Columns[colID].ColumnName + ",";
                InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ",";
            }
        }

        InsertSql = InsertSql_1 + InsertSql_2;

        //遍历数据表的所有数据行
        for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
        {
            for (int colID = 0; colID < ColCount; colID++)
            {
                if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")
                {
                    para[colID].Value = 0;
                }
                else
                {
                    para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();
                }
            }
            try
            {
                objCmd.CommandText = InsertSql;
                objCmd.ExecuteNonQuery();
            }
            catch (Exception exp)
            {
                string str = exp.Message;
            }
        }
        try
        {
            if (objConn.State == ConnectionState.Open)
            {
                objConn.Close();
            }
        }
        catch (Exception exp)
        {
            throw exp;
        }
        return true;
    }

原文地址:https://www.cnblogs.com/zhang9418hn/p/2320398.html