zoukankan      html  css  js  c++  java
  • 钉钉接口 给用户发钉盘文件消息 钉盘文件上传

    钉钉接口 给用户发钉盘文件消息

      步骤概括:  

    1. 创建一个用于企业内部开发的H5微应用。将文件发送给指定用户,用户将收到以次应用名义发送的一条文件消息
    2. 服务端调用“单步上传文件”接口,上传文件获取mediaId
    3. 服务端调用“发送钉盘文件给指定用户”接口,把钉盘文件当做消息内容发送给用户

    这里省略创建微应用的步骤。

    步骤1:获取access_token  (GET)

      请求地址:https://oapi.dingtalk.com/gettoken?appkey=key&appsecret=secret

      

      返回说明

    {
        "errcode": 0,
        "errmsg": "ok",
        "access_token": "fw8ef8we8f76e6f7s8df8s"
    }

    步骤2:调用“单步上传文件”接口,上传文件获取mediaId (POST)

      请求地址:https://oapi.dingtalk.com/file/upload/single?access_token=ACCESS_TOKEN&agent_id=AGENT_ID&file_size=FILE_SIZE 

      文件大小 取字节;

      

       返回说明

    {
        "media_id": "xxxxxxxx",
        "errcode":0,
        "errmsg":"ok"
    }

    步骤3:发送钉盘文件给指定用户(POST)

      请求地址:https://oapi.dingtalk.com/cspace/add_to_single_chat?access_token=ACCESS_TOKEN&agent_id=AGENT_ID&userid=USERID&media_id=MEDIA_ID&file_name=FILE_NAME

      

      media_id 和file_name需要转成urlEncode格式,{"errcode":40007,"errmsg":"不合法的媒体文件id"}除了media_id 不存在、为空,还有一个原因是因为没有转格式

      引用 System.Web.HttpUtility;

      HttpUtility.UrlEncode(" 内容 "); 

       返回结果

    {
        "errcode":0,
        "errmsg":"ok"
    }

    下面贴上代码:

    using System.Text;
    using System.IO;
    using System.Data;
    using System.Collections;
    using TWays.Core.DBAccess;
    using Newtonsoft.Json;
    
    public class DDManager
        {
            #region 公共方法
    
            /// <summary>
            /// 记录日志
            /// </summary>
            /// <param name="strMsg"></param>
            private void Logger(string strMsg)
            {
                string strFilePath = System.Windows.Forms.Application.StartupPath + "\" + StaticConst.WxSendLog;
                TWays.Core.Loger.LogMessage(strFilePath, strMsg, true);
            }
    
            //我这里是把钉钉的一些信息存在了数据库里
            //像APP_KEY、APP_SECRET之类的,根据自己定义的类型读取信息
            private DataSet GetValue(string type)
            {
                DataSet dr = DataAdapter.Query(string.Format(SqlText.selectDDTypeValue.ToUpper(), type));
    
                return dr;
            }
    
            #endregion
    
            #region 获取配置信息
    
    
            /// <summary>
            /// 获取微应用名称
            /// </summary>
            /// <returns></returns>
            public string GetAppMicorName(string type)
            {
                DataSet ds = GetValue(type);
                if (ds.Tables[0].Rows.Count < 0) return null;
    
                return TWays.Utils.ToString(ds.Tables[0].Rows[0]["DIC_NAME"]);
            }
    
            /// <summary>
            /// 获取APP_KEY
            /// </summary>
            /// <returns></returns>
            public string GetDDAppKey(string type)
            {
                //return GetConfigValue(StaticConst.WX_APP_ID);
                DataSet ds = GetValue(type);
                if (ds.Tables[0].Rows.Count < 0) return null;
    
                return TWays.Utils.ToString(ds.Tables[0].Rows[0]["APP_KEY"]);
            }
    
            /// <summary>
            /// 获取APP_SECRET
            /// </summary>
            /// <returns></returns>
            public string GetDDAppSecret(string type)
            {
                //return GetConfigValue(StaticConst.WX_APP_SECRET);
                DataSet ds = GetValue(type);
                if (ds.Tables[0].Rows.Count < 0) return null;
    
                return TWays.Utils.ToString(ds.Tables[0].Rows[0]["APP_SECRET"]);
            }
    
            /// <summary>
            /// 获取微应用id AGEN_ID
            /// </summary>
            /// <returns></returns>
            public string GetDDAgenId(string type)
            {
                //return GetConfigValue(StaticConst.WX_QY_CORP_ID);
                DataSet ds = GetValue(type);
                if (ds.Tables[0].Rows.Count < 0) return null;
    
                return TWays.Utils.ToString(ds.Tables[0].Rows[0]["AGEN_ID"]);
            }
    
            /// <summary>
            /// 获取配置信息
            /// </summary>
            /// <param name="strKey"></param>
            /// <returns></returns>
            public string GetConfigValue(string strKey)
            {
                string strKeyValue = string.Empty;
    
                strKeyValue = TWays.Utils.ToString(System.Configuration.ConfigurationManager.AppSettings[strKey]);
    
                return strKeyValue;
            }
    
            #endregion
    
            #region 获取POST消息
    
            /// <summary>
            /// 获取post返回来的数据
            /// </summary>
            /// <returns></returns>
            public static string PostInput()
            {
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                return Encoding.UTF8.GetString(b);
            }
    
            #endregion
    
            #region 获取企业号AccessToken
    
            public string GetQyAccessToken(string type)
            {
                string QY_AppKey = this.GetDDAppKey(type);//钉钉的APP_KEY
                string QY_AppSecret = this.GetDDAppSecret(type);//
    
                string url = string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}", QY_AppKey, QY_AppSecret);
                return ToAccessTokenJson(HttpRequestUtil.GetAppPage(url, 5000, Encoding.UTF8));
            }
    
            public string ToAccessTokenJson(string val)
            {
                AccessToken deserializedToken = (AccessToken)JavaScriptConvert.DeserializeObject(val, typeof(AccessToken));
                return deserializedToken.access_token;
            }
    
            #endregion
    
            #region 获取MediaId
    
            public string GetQyMediaId(string type, decimal size, string path)
            {
                string QY_MediaId = string.Empty;
    
                string strAccessToken = this.GetQyAccessToken(type);
                string strAgenId = this.GetDDAgenId(type);
    
                string url = string.Format("https://oapi.dingtalk.com/file/upload/single?access_token={0}&agent_id={1}&file_size={2}", strAccessToken, strAgenId, size);
    
                QY_MediaId = ToAccessMediaId(HttpRequestUtil.HttpPosturl(path, url));
    
                return QY_MediaId;
            }
            public string ToAccessMediaId(string val)
            {
                ThumbMedia deserializedMediaId = (ThumbMedia)JavaScriptConvert.DeserializeObject(val, typeof(ThumbMedia));
                return deserializedMediaId.media_id;
            }
    
    
            #endregion
    
            #region 获取用户id(判断用户是否存在)
    
            public string GetQyUserId(string token, string userId)
            {
                string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", token, userId);
                return ToUserJson(HttpRequestUtil.GetAppPage(url, 5000, Encoding.UTF8));
            }
    
            public string ToUserJson(string val)
            {
    
                Hashtable t = (Hashtable)JavaScriptConvert.DeserializeObject(val, typeof(Hashtable));
    
                if (t["errcode"].ToString() == "0")
                {
                    return t["userid"].ToString();
                }
                return "";
    
                //User deserializedToken = (User)JavaScriptConvert.DeserializeObject(val, typeof(User));
                //return deserializedToken.userid;
            }
    
            #endregion
    
        }    
    DDManager
    public class ExportExcel
        {
    
            public static void ExportToText(System.Data.DataTable dt, String filename)
            {
                ExportToText(dt, filename, false);
            }
    
            /// <summary>
            /// 快速导出文本
    
    
            /// </summary>
            /// <param name="devXtraGrid"></param>
            /// <param name="filename"></param>
            public static void ExportToText(System.Data.DataTable dt, String filename, bool isFirst)
            {
                if (dt == null) return;
    
                string strPath = filename;
    
                try
                {
                    //先打印标头
    
    
                    StringBuilder strColu = new StringBuilder();
                    StringBuilder strValue = new StringBuilder();
    
                    string strColText = string.Empty;
                    string strColHeadText = string.Empty;
    
                    StreamWriter sw = null;
    
                    if (File.Exists(filename))
                    {
                        sw = new StreamWriter(new FileStream(strPath, FileMode.Append), Encoding.GetEncoding("GB2312"));
                    }
                    else
                    {
                        sw = new StreamWriter(new FileStream(strPath, FileMode.Create), Encoding.GetEncoding("GB2312"));
                    }
                    using (sw)
                    {
    
                        sw.AutoFlush = true;
    
                        if (isFirst)
                        {
                            //先打印表头
    
                            for (int i = 0; i <= dt.Columns.Count - 1; i++)
                            {
                                strColHeadText = dt.Columns[i].ColumnName;
                                if (string.IsNullOrEmpty(strColHeadText))
                                {
                                    strColHeadText = TWays.Utils.ToString(dt.Columns[i].ColumnName);
                                }
                                strColu.Append(strColHeadText);
                                strColu.Append("	");
                            }
                            strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
                        }
    
                        sw.WriteLine(strColu);
    
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            DataRow dr = dt.Rows[i];
                            if (dr != null)
                            {
                                strValue.Remove(0, strValue.Length);//移出
    
                                for (int j = 0; j <= dt.Columns.Count - 1; j++)
                                {
                                    strColText = string.Empty;
                                    if (dr[j] != null)
                                    {
                                        strColText = dr[j].ToString();
                                    }
    
                                    strValue.Append(strColText);
                                    strValue.Append("	");
                                }
                                strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                                sw.WriteLine(strValue);
                            }
                        }
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    
            /// <summary>
            /// 快速导出文本
    
    
            /// </summary>
            /// <param name="devXtraGrid"></param>
            /// <param name="filename"></param>
            public static void ExportToTextForBudget(System.Data.DataTable dt, System.Data.DataTable dtDate, String filename)
            {
                if (dt == null) return;
    
                string strPath = filename;
    
                try
                {
                    //先打印标头
    
                    bool isFirst = true;
    
                    StringBuilder strColu = new StringBuilder();
                    StringBuilder strValue = new StringBuilder();
    
                    string strColText = string.Empty;
                    string strColHeadText = string.Empty;
    
                    StreamWriter sw = null;
    
                    if (File.Exists(filename))
                    {
                        sw = new StreamWriter(new FileStream(strPath, FileMode.Append), Encoding.GetEncoding("GB2312"));
                    }
                    else
                    {
                        sw = new StreamWriter(new FileStream(strPath, FileMode.Create), Encoding.GetEncoding("GB2312"));
                    }
                    using (sw)
                    {
    
                        sw.AutoFlush = true;
    
                        if (isFirst)
                        {
                            string strAmtColName = string.Empty;
                            //先打印表头
    
                            for (int i = 0; i <= dt.Columns.Count - 1; i++)
                            {
                                strColHeadText = dt.Columns[i].ColumnName;
                                if (strColHeadText.ToUpper().Contains("_AMT_"))
                                {
                                    DataRow[] dr = dtDate.Select("COLUMN_NAME = '" + strColHeadText + "'");
                                    if (dr.Length > 0)
                                    {
                                        strColHeadText = TWays.Utils.ToString(dr[0]["COLUMN_VALUE"]);
                                    }
                                }
                                else if (strColHeadText.ToUpper().Contains("A"))
                                {
                                    strColHeadText = strColHeadText.Replace("A", "");
                                }
                                strColu.Append(strColHeadText);
                                strColu.Append("	");
                            }
                            strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
                        }
    
                        sw.WriteLine(strColu);
    
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            DataRow dr = dt.Rows[i];
                            if (dr != null)
                            {
                                strValue.Remove(0, strValue.Length);//移出
    
                                for (int j = 0; j <= dt.Columns.Count - 1; j++)
                                {
                                    strColText = string.Empty;
                                    if (dr[j] != null)
                                    {
                                        strColText = dr[j].ToString();
                                    }
    
                                    strValue.Append(strColText);
                                    strValue.Append("	");
                                }
                                strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                                sw.WriteLine(strValue);
                            }
                        }
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    
            /// <summary>
            /// 通过StreamWriter写
    
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="dsWeek"></param>
            /// <param name="strOperDate"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static bool WriteToText(DataSet dataSet, DataSet dsWeek, string strOperDate, string fileName, bool isFirst)
            {
                string strPath = fileName;
    
                System.Data.DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;//不包括字段名 
    
                if (rowNumber == 0)
                {
                    return false;
                }
    
                StringBuilder sb = new StringBuilder();
                StringBuilder sbValue = new StringBuilder();
    
                StreamWriter sw = null;
    
                if (File.Exists(fileName))
                {
                    sw = new StreamWriter(new FileStream(strPath, FileMode.Append), Encoding.GetEncoding("GB2312"));
                }
                else
                {
                    sw = new StreamWriter(new FileStream(strPath, FileMode.Create), Encoding.GetEncoding("GB2312"));
                }
    
                using (sw)
                {
                    string strColName = string.Empty;
                    string[] strWeekNum;
                    int iWeekNum;
                    string strWeekColName = string.Empty;
    
                    sw.AutoFlush = true;
    
                    try
                    {
                        if (isFirst)
                        {
                            int iColIndex = 0;
                            //生成字段名称 
                            foreach (DataColumn col in dataTable.Columns)
                            {
                                strColName = col.ColumnName;
    
                                if (strColName.Contains("WEEK_"))
                                {
                                    strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                                    iWeekNum = Convert.ToInt32(strWeekNum[2]);
                                    strWeekColName = Convert.ToDateTime(TWays.Utils.ToString(dsWeek.Tables[0].Select(" WEEK_NUM = " + iWeekNum + " AND YEAR =" + Convert.ToInt32(strWeekNum[1]))[0]["BEGIN_DATE"])).ToString("MM/dd");
                                    strColName = strWeekColName;
                                }
                                else if (strColName.Contains("DAY_"))
                                {
                                    strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                                    iWeekNum = Convert.ToInt32(strWeekNum[1]);
                                    strWeekColName = Convert.ToDateTime(strOperDate).AddDays(-iWeekNum).ToString("MM/dd");
                                    strColName = strWeekColName;
                                }
    
                                sb.Append(strColName);
                                sb.Append("	");
                                iColIndex++;
    
                            }
                            sb.Remove(sb.Length - 1, 1);//移出掉最后一个,字符
                            sw.WriteLine(sb);
                        }
    
                        string strValue = string.Empty;
    
                        //生成数据
                        for (int i = 0; i < dataTable.Rows.Count; i++)
                        {
                            sbValue.Remove(0, sbValue.Length);//移出
    
                            for (int j = 0; j < dataTable.Columns.Count; j++)
                            {
                                strValue = TWays.Utils.ToString(dataTable.Rows[i][j]);
                                strValue = strValue.Replace("
    ", "");
                                strValue = strValue.Replace("
    ", "");
                                strValue = strValue.Replace("	", "");
                                strValue = strValue.Replace(""", "");
    
                                sbValue.Append(strValue);
                                sbValue.Append("	");
                            }
                            sbValue.Remove(sbValue.Length - 1, 1);//移出掉最后一个,字符 
                            sw.WriteLine(sbValue);
                        }
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        sw = null;
                        sb = null;
                        dataTable = null;
                        dataSet = null;
                        dsWeek = null;
                        GC.Collect();
                    }
                }
                return true;
    
            }
    
            /// <summary>
            /// 添加到压缩文件
    
            /// </summary>
            /// <param name="strzipPath"></param>
            /// <param name="strtxtPath"></param>
            /// <returns></returns>
            public static string CreateRar(string strzipPath, string strtxtPath)
            {
                string strResult = string.Empty;
                try
                {
                    if (File.Exists(strzipPath))
                    {
                        File.Delete(strzipPath);
                    }
                    System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                    Process1.StartInfo.FileName = "Winrar.exe";
                    Process1.StartInfo.CreateNoWindow = true;
                    //Process1.StartInfo.Arguments = " a -r " + strzipPath + " " + strtxtPath;
                    Process1.StartInfo.Arguments = " a -ep " + strzipPath + " " + strtxtPath;
                    Process1.Start();
                }
                catch (Exception ex)
                {
                    strResult = ex.Message;
                }
                return strResult;
            }
    
            /// <summary>
            /// 导出到Excel
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static bool DataSetToExcel(DataSet dataSet, string fileName)
            {
                if (File.Exists(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    File.Delete(fileName);
                   
                }
                
                System.Data.DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;//不包括字段名 
                int columnNumber = dataTable.Columns.Count;
                int colIndex = 0;
    
                //if (rowNumber == 0)
                //{
                //    return false;
                //}
    
                //建立Excel对象 
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
                excel.Visible = false;
                Microsoft.Office.Interop.Excel.Range range;
                
                //生成字段名称 
                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;
                    excel.Cells[1, colIndex] = col.ColumnName;
                }
    
                object[,] objData = new object[rowNumber, columnNumber];
    
                for (int r = 0; r < rowNumber; r++)
                {
                    for (int c = 0; c < columnNumber; c++)
                    {
                        objData[r, c] = dataTable.Rows[r][c];
                    }
                }
               
                // 写入Excel 
                range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]);
                range.NumberFormat = "@";//设置单元格为文本格式 
                range.Value2 = objData;
                workbook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                
                try
                {
                    workbook.Saved = true;
                    excel.UserControl = false;
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    workbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);
                    excel.Quit();
    
                    workbook = null;
                    worksheet = null;
                    excel = null;
                    range = null;
                }
                return true;
            }
    
            /// <summary>
            /// 导出到Excel
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static bool DataSetToExcel(DataSet dataSet, DataSet dsWeek, string strOperDate, string fileName)
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
    
                System.Data.DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;//不包括字段名 
                int columnNumber = dataTable.Columns.Count;
                int colIndex = 0;
    
                if (rowNumber == 0)
                {
                    return false;
                }
    
                //建立Excel对象 
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
                excel.Visible = false;
                Microsoft.Office.Interop.Excel.Range range;
    
                string strColName = string.Empty;
                string[] strWeekNum;
                int iWeekNum;
                string strWeekColName = string.Empty;
    
                //生成字段名称 
                foreach (DataColumn col in dataTable.Columns)
                {
                    strColName = col.ColumnName;
    
                    if (strColName.Contains("WEEK_"))
                    {
                        strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                        iWeekNum = Convert.ToInt32(strWeekNum[2]);
                        strWeekColName = Convert.ToDateTime(TWays.Utils.ToString(dsWeek.Tables[0].Select(" WEEK_NUM = " + iWeekNum + " AND YEAR =" + Convert.ToInt32(strWeekNum[1]))[0]["BEGIN_DATE"])).ToString("MM/dd");
                        strColName = strWeekColName;
                    }
                    else if (strColName.Contains("DAY_"))
                    {
                        strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                        iWeekNum = Convert.ToInt32(strWeekNum[1]);
                        strWeekColName = Convert.ToDateTime(strOperDate).AddDays(-iWeekNum).ToString("MM/dd");
                        strColName = strWeekColName;
                    }
    
                    colIndex++;
                    excel.Cells[1, colIndex] = strColName;
                }
    
                object[,] objData = new object[rowNumber, columnNumber];
    
                for (int r = 0; r < rowNumber; r++)
                {
                    for (int c = 0; c < columnNumber; c++)
                    {
                        objData[r, c] = dataTable.Rows[r][c];
                    }
                }
    
                // 写入Excel 
                range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]);
                range.NumberFormat = "@";//设置单元格为文本格式 
                range.Value2 = objData;
                //range.Value = objData;
                workbook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    
                try
                {
                    workbook.Saved = true;
                    excel.UserControl = false;
                    GC.Collect();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    workbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);
                    excel.Quit();
    
                    workbook = null;
                    worksheet = null;
                    excel = null;
                    range = null;
                }
                return true;
            }
    
            /// <summary>
            /// 通过StreamWriter写
    
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="dsWeek"></param>
            /// <param name="strOperDate"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static bool WriteToExcel(DataSet dataSet, DataSet dsWeek, string strOperDate, string fileName)
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
    
                System.Data.DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;//不包括字段名 
    
                if (rowNumber == 0)
                {
                    return false;
                }
    
                StreamWriter sw = new StreamWriter(fileName, false, Encoding.GetEncoding("gb2312"));
                StringBuilder sb = new StringBuilder();
    
                string strColName = string.Empty;
                string[] strWeekNum;
                int iWeekNum;
                string strWeekColName = string.Empty;
    
                try
                {
                    int iColIndex = 0;
                    //生成字段名称 
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        strColName = col.ColumnName;
    
                        if (strColName.Contains("WEEK_"))
                        {
                            strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                            iWeekNum = Convert.ToInt32(strWeekNum[2]);
                            strWeekColName = Convert.ToDateTime(TWays.Utils.ToString(dsWeek.Tables[0].Select(" WEEK_NUM = " + iWeekNum + " AND YEAR =" + Convert.ToInt32(strWeekNum[1]))[0]["BEGIN_DATE"])).ToString("MM/dd");
                            strColName = strWeekColName;
                        }
                        else if (strColName.Contains("DAY_"))
                        {
                            strWeekNum = strColName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                            iWeekNum = Convert.ToInt32(strWeekNum[1]);
                            strWeekColName = Convert.ToDateTime(strOperDate).AddDays(-iWeekNum).ToString("MM/dd");
                            strColName = strWeekColName;
                        }
    
                        sb.Append(strColName);
    
                        if (iColIndex < dataTable.Columns.Count - 1)
                        {
                            sb.Append("	");
                        }
                        iColIndex++;
    
                    }
                    sb.Append(Environment.NewLine);
    
                    string strValue = string.Empty;
    
                    //生成数据
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        for (int j = 0; j < dataTable.Columns.Count; j++)
                        {
                            strValue = TWays.Utils.ToString(dataTable.Rows[i][j]);
                            strValue = strValue.Replace("
    ", "");
                            strValue = strValue.Replace("
    ", "");
                            strValue = strValue.Replace("	", "");
                            strValue = strValue.Replace(""", "");
    
                            sb.Append(strValue);
                            if (j < dataTable.Columns.Count - 1)
                                sb.Append("	");
                        }
                        sb.Append(Environment.NewLine);
                    }
                    sw.Write(sb.ToString());
                    sw.Flush();
                    sw.Close();
    
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sw = null;
                    sb = null;
                    dataTable = null;
                    dataSet = null;
                    dsWeek = null;
                    GC.Collect();
                }
                return true;
    
            }
    
            /// <summary>
            /// 通过StreamWriter写
    
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="dsWeek"></param>
            /// <param name="strOperDate"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static bool WriteToExcel(DataSet dataSet, string fileName)
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
    
                System.Data.DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;//不包括字段名 
    
                if (rowNumber == 0)
                {
                    return false;
                }
    
                StreamWriter sw = new StreamWriter(fileName, false, Encoding.GetEncoding("gb2312"));
                StringBuilder sb = new StringBuilder();
    
                string strColName = string.Empty;
    
                try
                {
                    int iColIndex = 0;
                    //生成字段名称 
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        strColName = col.ColumnName;
                        sb.Append(strColName);
    
                        if (iColIndex < dataTable.Columns.Count - 1)
                        {
                            sb.Append("	");
                        }
                        iColIndex++;
    
                    }
                    sb.Append(Environment.NewLine);
    
                    string strValue = string.Empty;
    
                    //生成数据
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        for (int j = 0; j < dataTable.Columns.Count; j++)
                        {
                            strValue = TWays.Utils.ToString(dataTable.Rows[i][j]);
                            strValue = strValue.Replace("
    ", "");
                            strValue = strValue.Replace("
    ", "");
                            strValue = strValue.Replace("	", "");
                            strValue = strValue.Replace(""", "");
    
                            sb.Append(strValue);
                            if (j < dataTable.Columns.Count - 1)
                                sb.Append("	");
                        }
                        sb.Append(Environment.NewLine);
                    }
                    sw.Write(sb.ToString());
                    sw.Flush();
                    sw.Close();
    
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sw = null;
                    sb = null;
                    dataTable = null;
                    dataSet = null;
                    GC.Collect();
                }
                return true;
    
            }
    
            public static System.Data.DataTable GetCsvData(string pCsvpath, string pCsvname)
            {
                try
                {
                    DataSet dsCsvData = new DataSet();
    
                    OleDbConnection OleCon = new OleDbConnection();
                    OleDbCommand OleCmd = new OleDbCommand();
                    OleDbDataAdapter OleDa = new OleDbDataAdapter();
    
                    OleCon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pCsvpath + ";Extended Properties='Text;FMT=Delimited(,);HDR=YES;IMEX=1';";
                    OleCon.Open();
                    System.Data.DataTable dts1 = OleCon.GetSchema("Tables");
                    System.Data.DataTable dts2 = OleCon.GetSchema("Columns");
                    OleCmd.Connection = OleCon;
                    OleCmd.CommandText = "select * from [" + pCsvname + "] where 1=1";
                    OleDa.SelectCommand = OleCmd;
                    OleDa.Fill(dsCsvData, "Table");
                    OleCon.Close();
    
                    return dsCsvData.Tables[0];
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }
    ExportExcel
        /// <summary>
        /// HTTP请求工具类
        /// </summary>
        public class HttpRequestUtil
        {
            #region 请求Url
    
            #region 请求Url,不发送数据POST
    
            /// <summary>
            /// 请求Url,不发送数据
            /// </summary>
            public static string RequestUrl(string url)
            {
                return RequestUrl(url, "POST");
            }
          
            public static string RequestUrl(string url, string method)
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 600000;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = method;
                request.ContentType = "text/html";
                request.Headers.Add("charset", "utf-8");
    
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
                //返回结果网页(html)代码
    
                string content = sr.ReadToEnd();
                return content;
            }
            #endregion
    
            #region 请求Url,不发送数据GET
    
            public static string GetAppPage(string url, int httpTimeout, Encoding postEncoding)
            {
                string rStr = "";
                System.Net.WebRequest req = null;
                System.Net.WebResponse resp = null;
                System.IO.Stream os = null;
                System.IO.StreamReader sr = null;
                try
                {
                    //创建连接
                    req = System.Net.WebRequest.Create(url);
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method = "GET";
    
                    //时间
                    if (httpTimeout > 0)
                    {
                        req.Timeout = httpTimeout;
                    }
    
                    //读取返回结果
                    resp = req.GetResponse();
                    sr = new System.IO.StreamReader(resp.GetResponseStream(), postEncoding);
                    rStr = sr.ReadToEnd();
                    rStr = rStr.Trim();         //除去空格
                }
                catch
                {
    
    
                }
                finally
                {
                    try
                    {
                        //关闭资源
                        if (os != null)
                        {
                            os.Dispose();
                            os.Close();
                        }
                        if (sr != null)
                        {
                            sr.Dispose();
                            sr.Close();
                        }
                        if (resp != null)
                        {
                            resp.Close();
                        }
                        if (req != null)
                        {
                            req.Abort();
                            req = null;
                        }
                    }
                    catch
                    {
    
                    }
                }
                return rStr;
    
            }
            
            #endregion
            
            #region 请求Url,发送数据
    
            /// <summary>
            /// 请求Url,发送数据
            /// </summary>
            public static string PostUrl(string url, string postData)
            {
                byte[] data = Encoding.UTF8.GetBytes(postData);
    
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.Timeout = 600000;
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                Stream outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
    
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页(html)代码
    
                string content = sr.ReadToEnd();
                return content;
            }
            #endregion
    
            #region 请求Url,上传文件
    
            public static string HttpPosturl(string filePath, string url)
            {
                string returnStr = string.Empty;
                using (WebClient client = new WebClient())
                {
                    byte[] data = client.UploadFile(url, filePath);
                    returnStr = Encoding.Default.GetString(data);
                }
    
                return returnStr;
            }
    
            #endregion
    
            #endregion
            
            #region Http下载文件
            /// <summary>
            /// Http下载文件
            /// </summary>
            public static string HttpDownloadFile(string url, string path)
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 600000;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
    
                //创建本地文件写入流
    
                Stream stream = new FileStream(path, FileMode.Create);
    
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                stream.Close();
                responseStream.Close();
                return path;
            }
            #endregion
    
            #region Http上传文件
            /// <summary>
            /// Http上传文件
            /// </summary>
            public static string HttpUploadFile(string url, string path)
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 600000;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
    
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("
    --" + boundary + "
    ");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("
    --" + boundary + "--
    ");
    
                int pos = path.LastIndexOf("\");
                string fileName = path.Substring(pos + 1);
    
                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name="file";filename="{0}"
    Content-Type:application/octet-stream
    
    ", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
    
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();
    
                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();
    
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页(html)代码
    
                string content = sr.ReadToEnd();
                return content;
            }
            #endregion
    
        }
    HTTP请求工具类
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Web;
    using TWays.Core.DBAccess;
    using System.IO;   
    
        /// <summary>
        ///  钉钉钉盘文件上传
        /// </summary>
        public class TransDDExcel
        {
    
            public TransDDExcel()
            {
                _Result = "";
            }
    
            private string _Result;    // 结果消息
            public string Result
            {
                get
                {
                    return _Result;
                }
                set
                {
                    _Result = value;
                }
            }
    
            public bool Process()
            {
                bool boolReturn = false;
    
                try
                {
                    //存在数据库中的同步日志,推送成功的不在推送
                    DataSet dsSucess = DataAdapter.Query(string.Format(SqlText.selectGmTransTaskLogSucess, "1003"));
                    if (dsSucess != null && dsSucess.Tables[0].Rows.Count > 0)
                    {
                        Nany.Web.Trans.BusiUtils.SaveLog(Constant.BsLogDirectory, "同步推送文件成功,无需再次同步。");
                        boolReturn = true;
                    }
                    else
                    {
                        #region
    
                        string sysDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                         //获取企业号AccessToken和微应用AGEN_ID
                        DDManager ddM = new DDManager();
                        string strToken = ddM.GetQyAccessToken(Constant.CST_DD_TYPE_FILE_PUSH);
                        string strAgenId = ddM.GetDDAgenId(Constant.CST_DD_TYPE_FILE_PUSH);
    
                        //获取根路径                    
                        string path = Nany.Web.Trans.BusiUtils.GetRootPath();
                        //组合两个路径字符串
                        path = Path.Combine(path, "TransExcel");
    
                        string strResult = string.Empty;
                        string countPath = string.Empty;
                        string customerOrderPath = string.Empty;
                        List<string> _Path = new List<string>();
                        List<string> _title = new List<string>();
               
                        //查询数据库中可接收文件的钉钉用户
                        DataSet dsAccount = DataAdapter.Query(string.Format(SqlText.selectDDAccount.ToUpper(), strAgenId));
                        if (dsAccount.Tables[0].Rows.Count <= 0)
                        {
                            Result = "没有需要推送文件的账户";
                            return false;
                        }
    
    
                        //收银客单分析                
                        DataSet dsPosCashInfo = DataAdapter.Query(string.Format(SqlText.selectDDPosCashAccount.ToUpper(), sysDate));
                        countPath = path + "\" + DateTime.Now.AddDays(-1).ToString("yyyyMMdd") + "收银客单分析.xlsx";
                        _Path.Add(countPath);
                        ExportExcel.DataSetToExcel(dsPosCashInfo, countPath);
                      
    
                        //组织客单分析
                        DataSet dsCustomerOrder = DataAdapter.Query(string.Format(SqlText.selectDDSelectOrgCustomerOrderAnalyze.ToUpper(), sysDate));
                        customerOrderPath = path + "\" + DateTime.Now.AddDays(-1).ToString("yyyyMMdd") + "组织客单分析.xlsx";
                        _Path.Add(customerOrderPath);
                        ExportExcel.DataSetToExcel(dsCustomerOrder, customerOrderPath);
    
    
                        //发送两个文件
                        _title.Add(DateTime.Now.AddDays(-1).ToString("yyyyMMdd") + "收银客单分析.xlsx");
                        _title.Add(DateTime.Now.AddDays(-1).ToString("yyyyMMdd") + "组织客单分析.xlsx");
    
                        int error = 0;
                        int success = 0;
    
                        for (int i = 0; i < dsAccount.Tables[0].Rows.Count; i++)
                        {
                            DataRow dr = dsAccount.Tables[0].Rows[i];
    
                            string userId = ddM.GetQyUserId(strToken, dr["DD_CODE"].ToString());
                            if (string.IsNullOrEmpty(userId))
                            {
                                error++;
                                Nany.Web.Trans.BusiUtils.SaveLog(Constant.BsLogDirectory, "钉钉账号【" + dr["DD_CODE"].ToString() + "】不存在");
                                //Result = "钉钉账号【" + dr["DD_CODE"].ToString() + "】不存在";
                                continue;
                            }
    
                            for (int t = 0; t < _Path.Count; t++)
                            {
    
                                //判断当前路径所指向的是否为文件
                                if (File.Exists(_Path[t]))
                                {
                                    //定义一个FileInfo对象,使之与filePath所指向的文件向关联,
                                    //以获取其大小
                                    FileInfo fileInfo = new FileInfo(_Path[t]);
                                    decimal size = fileInfo.Length;
                                    string strMediaId = ddM.GetQyMediaId(Constant.CST_DD_TYPE_FILE_PUSH, size, _Path[t]);
                                    //Nany.Web.Trans.BusiUtils.SaveLog(Constant.BsLogDirectory, _Path[t]);
    
                                    strResult = HttpRequestUtil.RequestUrl(string.Format("https://oapi.dingtalk.com/cspace/add_to_single_chat?access_token={0}&agent_id={1}&userid={2}&media_id={3}&file_name={4}",
                                        ddM.GetQyAccessToken(Constant.CST_DD_TYPE_FILE_PUSH), strAgenId, dr["DD_CODE"].ToString(), HttpUtility.UrlEncode(strMediaId), HttpUtility.UrlEncode(_title[t])));
    
                                    if (strResult.Contains(""errmsg":"ok""))
                                    {
                                        boolReturn = true;
                                        success++;
                                        //Result = "已向" + (success/2).ToString() + "位用户成功推送文件,失败" + error.ToString() + "位";
                                    }
                                    else
                                    {
                                        //Result = strResult;
                                        Nany.Web.Trans.BusiUtils.SaveLog(Constant.BsLogDirectory, strResult);
                                        boolReturn = false;
                                    }
                                }
    
                            }
    
                        }
    
                        Result = "已向" + (success / 2).ToString() + "位用户成功推送文件,失败" + error.ToString() + "";
    
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    Result = ex.Message;
                }
                return boolReturn;
            }
    
            public void Dispose()
            {
                GC.SuppressFinalize(this);
            }
        }
    发送钉盘文件给指定用户

     

      

  • 相关阅读:
    LeetCode 485. Max Consecutive Ones
    LeetCode 367. Valid Perfect Square
    LeetCode 375. Guess Number Higher or Lower II
    LeetCode 374. Guess Number Higher or Lower
    LeetCode Word Pattern II
    LeetCode Arranging Coins
    LeetCode 422. Valid Word Square
    Session 共享
    java NIO
    非阻塞IO
  • 原文地址:https://www.cnblogs.com/Swaggy-yyq/p/12191009.html
Copyright © 2011-2022 走看看