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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

钉钉接⼝给⽤户发钉盘⽂件消息钉盘⽂件上传
钉钉接⼝给⽤户发钉盘⽂件消息
步骤概括:
1. 创建⼀个⽤于企业内部开发的H5微应⽤。

将⽂件发送给指定⽤户,⽤户将收到以次应⽤名义发送的⼀条⽂件消息
2. 服务端调⽤“”接⼝,上传⽂件获取mediaId
3. 服务端调⽤“”接⼝,把钉盘⽂件当做消息内容发送给⽤户
这⾥省略创建微应⽤的步骤。

步骤1:获取access_token (GET)
返回说明
{
"errcode": 0,
"errmsg": "ok",
"access_token": "fw8ef8we8f76e6f7s8df8s"
}
步骤2:调⽤“”接⼝,上传⽂件获取mediaId (POST)
⽂件⼤⼩取字节;
返回说明
{
"media_id": "xxxxxxxx",
"errcode":0,
"errmsg":"ok"
}
步骤3:发送钉盘⽂件给指定⽤户(POST)
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获取配置信息
///<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:///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:///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;
}
#region获取⽤户id(判断⽤户是否存在)
public string GetQyUserId(string token, string userId)
{
string url = string.Format("https:///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 erid;
}
#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("\t");
}
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("\t");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后⼀个,字符
sw.WriteLine(strValue);
}
}
sw.Flush();
sw.Close();
sw.Dispose();
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("\t");
}
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("\t");
}
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;
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(" 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("\t");
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("\r", "");
strValue = strValue.Replace("\n", "");
strValue = strValue.Replace("\t", "");
strValue = strValue.Replace("\"", "");
sbValue.Append(strValue);
sbValue.Append("\t");
}
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);
//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, try
{
workbook.Saved = true;
erControl = 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;
//⽣成字段名称
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, try
{
workbook.Saved = true;
erControl = 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("\t");
}
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("\r", "");
strValue = strValue.Replace("\n", "");
strValue = strValue.Replace("\t", "");
strValue = strValue.Replace("\"", "");
sb.Append(strValue);
if (j < dataTable.Columns.Count - 1)
sb.Append("\t");
}
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("\t");
}
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("\r", "");
strValue = strValue.Replace("\n", "");
strValue = strValue.Replace("\t", "");
strValue = strValue.Replace("\"", "");
sb.Append(strValue);
if (j < dataTable.Columns.Count - 1)
sb.Append("\t");
}
sb.Append(Environment.NewLine);
}
sw.Write(sb.ToString());
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
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;
mandText = "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 = "";
.WebRequest req = null;
.WebResponse resp = null;
System.IO.Stream os = null;
System.IO.StreamReader sr = null;
try
{
//创建连接
req = .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
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)
{。

相关文档
最新文档