You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1033 lines
36 KiB

2 years ago
  1. using Entity.Sugar;
  2. using Newtonsoft.Json.Linq;
  3. using SqlSugar;
  4. using SqlSugar.Base;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Net;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Web;
  16. using System.Xml;
  17. using DocumentFormat.OpenXml.Wordprocessing;
  18. using DocumentFormat.OpenXml.Packaging;
  19. using System.Linq;
  20. namespace EasyBL
  21. {
  22. /// <summary>
  23. /// Common 的摘要描述
  24. /// </summary>
  25. public class Common
  26. {
  27. #region GetAppSettings
  28. /// <summary>
  29. /// 獲取WebService的配置信息
  30. /// </summary>
  31. /// <param name="sKey">todo: describe sKey parameter on GetAppSettings</param>
  32. /// <example></example>
  33. /// <returns>appSettings中配置的value值</returns>
  34. public static string GetAppSettings(string sKey)
  35. {
  36. var sVal = ConfigurationManager.AppSettings[sKey];
  37. return sVal ?? @"";
  38. }
  39. #endregion GetAppSettings
  40. #region UpdateAppSettings
  41. /// <summary>
  42. /// 修改config配置
  43. /// </summary>
  44. /// <param name="sKey">todo: describe sKey parameter on UpdateAppSettings</param>
  45. /// <param name="sValue">todo: describe sValue parameter on UpdateAppSettings</param>
  46. /// <returns></returns>
  47. public static bool UpdateAppSettings(string sKey, string sValue)
  48. {
  49. var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  50. if (!config.HasFile)
  51. {
  52. throw new ArgumentException(@"程序配置文件缺失!");
  53. }
  54. var _key = config.AppSettings.Settings[sKey];
  55. if (_key == null)
  56. config.AppSettings.Settings.Add(sKey, sValue);
  57. else
  58. config.AppSettings.Settings[sKey].Value = sValue;
  59. config.Save(ConfigurationSaveMode.Modified);
  60. return true;
  61. }
  62. #endregion UpdateAppSettings
  63. #region ConfigSetValue
  64. /// <summary>
  65. /// 写操作
  66. /// </summary>
  67. /// <param name="sExecutablePath">todo: describe sExecutablePath parameter on ConfigSetValue</param>
  68. /// <param name="sKey">todo: describe sKey parameter on ConfigSetValue</param>
  69. /// <param name="sValue">todo: describe sValue parameter on ConfigSetValue</param>
  70. public static void ConfigSetValue(string sExecutablePath, string sKey, string sValue)
  71. {
  72. if (!Directory.Exists(sExecutablePath))
  73. {
  74. sExecutablePath = System.Windows.Forms.Application.StartupPath.ToString();
  75. }
  76. var xDoc = new XmlDocument();
  77. //获取可执行文件的路径和名称
  78. xDoc.Load(sExecutablePath + @".config");
  79. XmlNode xNode;
  80. XmlElement xElem1;
  81. XmlElement xElem2;
  82. xNode = xDoc.SelectSingleNode(@"//connectionStrings");
  83. // xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
  84. xElem1 = (XmlElement)xNode.SelectSingleNode(@"//add[@name='" + sKey + @"']");
  85. if (xElem1 != null) xElem1.SetAttribute(@"connectionString", sValue);
  86. else
  87. {
  88. xElem2 = xDoc.CreateElement(@"add");
  89. xElem2.SetAttribute(@"name", sKey);
  90. xElem2.SetAttribute(@"connectionString", sValue);
  91. xNode.AppendChild(xElem2);
  92. }
  93. xDoc.Save(sExecutablePath + @"Euro.Transfer.exe.config");
  94. }
  95. #endregion ConfigSetValue
  96. #region ConfigGetValue
  97. /// <summary>
  98. /// 读操作
  99. /// </summary>
  100. /// <param name="sExecutablePath">todo: describe sExecutablePath parameter on ConfigGetValue</param>
  101. /// <param name="sKey">todo: describe sKey parameter on ConfigGetValue</param>
  102. /// <returns></returns>
  103. public static string ConfigGetValue(string sExecutablePath, string sKey)
  104. {
  105. if (!Directory.Exists(sExecutablePath))
  106. {
  107. sExecutablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  108. }
  109. var xDoc = new XmlDocument();
  110. try
  111. {
  112. xDoc.Load(sExecutablePath + @"Web.config");
  113. XmlNode xNode;
  114. XmlElement xElem;
  115. xNode = xDoc.SelectSingleNode(@"//appSettings");
  116. xElem = (XmlElement)xNode.SelectSingleNode(@"//add[@key='" + sKey + @"']");
  117. if (xElem != null)
  118. return xElem.GetAttribute(@"value");
  119. else
  120. return @"";
  121. }
  122. catch (Exception)
  123. {
  124. return @"";
  125. }
  126. }
  127. #endregion ConfigGetValue
  128. #region FnDataSetToDataTable
  129. /// <summary>
  130. /// 返回DataSet中第一個DataTable
  131. /// </summary>
  132. /// <param name="ds">需要轉換的DataSet</param>
  133. /// <returns></returns>
  134. public static DataTable FnDataSetToDataTable(DataSet ds)
  135. {
  136. var dt = new DataTable();
  137. if (ds != null && ds.Tables.Count > 0)
  138. {
  139. dt = ds.Tables[0];
  140. }
  141. return dt;
  142. }
  143. #endregion FnDataSetToDataTable
  144. #region FnDataSetToDataTable
  145. /// <summary>
  146. /// 返回DataSet中第一個DataTable
  147. /// </summary>
  148. /// <param name="ds">需要轉換的DataSet</param>
  149. /// <param name="sTableName">todo: describe sTableName parameter on FnDataSetToDataTable</param>
  150. /// <returns></returns>
  151. public static DataTable FnDataSetToDataTable(DataSet ds, string sTableName)
  152. {
  153. var dt = new DataTable();
  154. if (ds != null && ds.Tables.Count > 0 && ds.Tables[sTableName] != null)
  155. {
  156. dt = ds.Tables[sTableName];
  157. }
  158. return dt;
  159. }
  160. #endregion FnDataSetToDataTable
  161. #region FnDateDiffDay
  162. /// <summary>
  163. /// 取得時間差(天),超過y
  164. /// </summary>
  165. /// <param name="rDateTime1">todo: describe rDateTime1 parameter on FnDateDiffDays</param>
  166. /// <param name="rDateTime2">todo: describe rDateTime2 parameter on FnDateDiffDays</param>
  167. /// <returns></returns>
  168. public static int FnDateDiffDays(DateTime rDateTime1, DateTime rDateTime2)
  169. {
  170. var dateDiffDays = 0;
  171. var ts1 = new TimeSpan(Convert.ToDateTime(rDateTime1.ToString(@"yyyy/MM/dd")).Ticks);
  172. var ts2 = new TimeSpan(Convert.ToDateTime(rDateTime2.ToString(@"yyyy/MM/dd")).Ticks);
  173. var ts = ts1.Subtract(ts2).Duration();
  174. dateDiffDays = ts.Days + 1;
  175. return dateDiffDays;
  176. }
  177. #endregion FnDateDiffDay
  178. #region FnDateDiffHours
  179. /// <summary>
  180. /// 取得時間差(小時),超過y
  181. /// </summary>
  182. /// <param name="rDateTime1">todo: describe rDateTime1 parameter on FnDateDiffHours</param>
  183. /// <param name="rDateTime2">todo: describe rDateTime2 parameter on FnDateDiffHours</param>
  184. /// <returns></returns>
  185. public static int FnDateDiffHours(DateTime rDateTime1, DateTime rDateTime2)
  186. {
  187. var dateDiffHours = 0;
  188. var ts1 = new TimeSpan(rDateTime1.Ticks);
  189. var ts2 = new TimeSpan(rDateTime2.Ticks);
  190. var ts = ts1.Subtract(ts2).Duration();
  191. dateDiffHours = ts.Hours;
  192. return dateDiffHours;
  193. }
  194. #endregion FnDateDiffHours
  195. #region DateToTw
  196. /// <summary>
  197. /// 西元年轉民國年
  198. /// </summary>
  199. /// <param name="sYDate">todo: describe sYDate parameter on DateToTw</param>
  200. /// <returns>民國年</returns>
  201. public static string DateToTw(string sYDate)
  202. {
  203. var strDate = @"";
  204. string[] aryTmp;
  205. try
  206. {
  207. //檢查民國或民國前 (民國元年1912、民國前1年1911)
  208. var oDate = DateTime.Parse(sYDate);
  209. var blnPN = ((oDate.Year - 1911) > 0 ? true : false);
  210. if (blnPN)
  211. {
  212. //民國
  213. var twCultureInfo = new CultureInfo(@"zh-TW");
  214. twCultureInfo.DateTimeFormat.Calendar = new TaiwanCalendar();
  215. strDate = DateTime.Parse(sYDate).Date.ToString(@"d", twCultureInfo);
  216. if (oDate.Year < 1921)
  217. {
  218. aryTmp = SplitString(strDate, @"/");
  219. strDate = $@"{int.Parse(aryTmp[0])}{oDate:M/d}";
  220. }
  221. }
  222. else
  223. {
  224. //民國前
  225. strDate = $@"{(oDate.Year - 1911 - 1)}/{oDate:M/d}";
  226. }
  227. return strDate;
  228. }
  229. catch (Exception)
  230. {
  231. return @"";
  232. }
  233. }
  234. #endregion DateToTw
  235. #region DateToYYYY
  236. /// <summary>
  237. /// 民國年轉西元年
  238. /// </summary>
  239. /// <param name="sYDate">todo: describe sYDate parameter on DateToYYYY</param>
  240. /// <returns>西元年</returns>
  241. public static string DateToYYYY(string sYDate)
  242. {
  243. var strDate = @"";
  244. try
  245. {
  246. //檢查民國或民國前 (民國元年1912、民國前1年1911)
  247. var strPN = sYDate.Substring(0, 1).Trim();
  248. switch (strPN)
  249. {
  250. case @"-":
  251. //民國前
  252. var aryTmp = SplitString(sYDate, @"/");
  253. strDate = $@"{(1911 + int.Parse(aryTmp[0]) + 1)}/{aryTmp[1]}/{aryTmp[2]}";
  254. break;
  255. default:
  256. if (strPN == @"+" || strPN == @"-")
  257. sYDate = sYDate.Substring(1);
  258. //民國
  259. var twCultureInfo = new CultureInfo(@"zh-TW");
  260. twCultureInfo.DateTimeFormat.Calendar = new TaiwanCalendar();
  261. //民國年2位轉3位----------------------------add by bruce 20140715
  262. var tw_ary = sYDate.Split('/');
  263. if (tw_ary.Length > 0)
  264. {
  265. var tw_yyy = tw_ary[0];
  266. if (tw_yyy.Length == 2) sYDate = @"0" + sYDate;
  267. }
  268. //民國年2位轉3位----------------------------add by bruce 20140715
  269. strDate = DateTime.Parse(sYDate, twCultureInfo).Date.ToString(@"d");
  270. break;
  271. }
  272. return strDate;
  273. }
  274. catch (Exception)
  275. {
  276. return @"";
  277. }
  278. }
  279. public static string[] SplitString(string sStr, string delimiter)
  280. {
  281. string[] split = null;
  282. var delimit = delimiter.ToCharArray();
  283. split = sStr.Split(delimit);
  284. return split;
  285. }
  286. #endregion DateToYYYY
  287. #region GetSystemSetting
  288. /// <summary>
  289. /// 獲取系統設定
  290. /// </summary>
  291. /// <param name="db">todo: describe db parameter on GetSystemSetting</param>
  292. /// <param name="sOrgID">todo: describe sOrgID parameter on GetSystemSetting</param>
  293. /// <param name="sItemID">todo: describe sItemID parameter on GetSystemSetting</param>
  294. /// <returns></returns>
  295. public static string GetSystemSetting(SqlSugarClient db, string sOrgID, string sItemID)
  296. {
  297. var sSettingValue = string.Empty;
  298. if (!string.IsNullOrWhiteSpace(sOrgID) && !string.IsNullOrWhiteSpace(sItemID))
  299. {
  300. try
  301. {
  302. var oSet = db.Queryable<OTB_SYS_SystemSetting>().Single(it => it.OrgID == sOrgID && it.SettingItem == sItemID);
  303. if (oSet != null)
  304. {
  305. sSettingValue = oSet.SettingValue;
  306. }
  307. }
  308. catch (Exception ex)
  309. {
  310. LogService.MailSend(ex.Message + @" sOrgID:" + sOrgID + @";sItemID:" + sItemID, ex, @"", @"", @"EasyBL.Common.GetSystemSetting", nameof(Common), @"GetSystemSetting(獲取系統設定)", @"", @"", @"");
  311. }
  312. }
  313. return sSettingValue;
  314. }
  315. #endregion GetSystemSetting
  316. #region GetSystemSettings
  317. /// <summary>
  318. /// 獲取系統設定(多值)
  319. /// </summary>
  320. /// <param name="sOrgID">todo: describe sOrgID parameter on GetSystemSettings</param>
  321. /// <param name="skeys">todo: describe skeys parameter on GetSystemSettings</param>
  322. /// <returns></returns>
  323. public static EasyNet.Common.Map GetSystemSettings(string sOrgID, string[] skeys)
  324. {
  325. var mSettingItem = new EasyNet.Common.Map();
  326. if (!string.IsNullOrWhiteSpace(sOrgID) && skeys.Length > 0)
  327. {
  328. try
  329. {
  330. var db = SugarBase.GetIntance();
  331. var list = db.Queryable<OTB_SYS_SystemSetting>().Where(it => it.OrgID == sOrgID && it.Effective == @"Y" && SqlFunc.ContainsArray(skeys, it.SettingItem)).ToList();
  332. foreach (OTB_SYS_SystemSetting set in list)
  333. {
  334. mSettingItem.Put(set.SettingItem, set.SettingValue);
  335. }
  336. }
  337. catch (Exception ex)
  338. {
  339. LogService.MailSend(ex.Message + @" sOrgID:" + sOrgID + @";sItemID:" + skeys, ex, @"", @"", @"Common.GetSystemSettings", nameof(Common), @"GetSystemSettings(獲取系統設定(多值))", @"", @"", @"");
  340. }
  341. }
  342. return mSettingItem;
  343. }
  344. #endregion GetSystemSettings
  345. #region ToDataTable
  346. /// <summary>
  347. /// DataRow轉換table
  348. /// </summary>
  349. /// <param name="dr">todo: describe dr parameter on ToDataTable</param>
  350. public static DataTable ToDataTable(DataRow[] dr)
  351. {
  352. if (dr == null || dr.Length == 0) return null;
  353. var tmp = dr[0].Table.Clone(); // 复制DataRow的表结构
  354. foreach (DataRow row in dr)
  355. tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
  356. return tmp;
  357. }
  358. #endregion ToDataTable
  359. #region FnCopyFile
  360. /// <summary>
  361. /// 複製文件
  362. /// </summary>
  363. /// <param name="sFromFullPath">todo: describe sFromFullPath parameter on FnCopyFile</param>
  364. /// <param name="sToFullPath">todo: describe sToFullPath parameter on FnCopyFile</param>
  365. public static void FnCopyFile(string sFromFullPath, string sToFullPath)
  366. {
  367. //strFromFullPath = Server.MapPath(strFromFullPath);
  368. if (File.Exists(sFromFullPath))
  369. {
  370. if (File.Exists(sToFullPath))
  371. {
  372. sToFullPath = sToFullPath.Insert(sToFullPath.LastIndexOf(@".") - 1, @"(1)");
  373. File.Copy(sFromFullPath, sToFullPath, false);
  374. }
  375. else
  376. {
  377. File.Copy(sFromFullPath, sToFullPath);
  378. }
  379. }
  380. }
  381. #endregion FnCopyFile
  382. #region FnCreateDir
  383. /// <summary>
  384. /// 創建目錄
  385. /// </summary>
  386. /// <param name="sPath">todo: describe sPath parameter on FnCreateDir</param>
  387. public static void FnCreateDir(string sPath)
  388. {
  389. if (!Directory.Exists(sPath))
  390. {
  391. Directory.CreateDirectory(sPath);
  392. }
  393. }
  394. #endregion FnCreateDir
  395. #region FnDeleteDir
  396. /// <summary>
  397. /// 删除文件夹
  398. /// </summary>
  399. /// <param name="sPath">todo: describe sPath parameter on FnDeleteDir</param>
  400. public static void FnDeleteDir(string sPath)
  401. {
  402. if (Directory.Exists(sPath))
  403. {
  404. Directory.Delete(sPath);
  405. }
  406. }
  407. #endregion FnDeleteDir
  408. #region FnDeletePathFiles
  409. /// <summary>
  410. /// 删除文件夹內文件
  411. /// </summary>
  412. /// <param name="sPath">todo: describe sPath parameter on FnDeletePathFiles</param>
  413. public static void FnDeletePathFiles(string sPath)
  414. {
  415. foreach (string file in Directory.GetFiles(sPath))
  416. {
  417. File.Delete(file);
  418. }
  419. }
  420. #endregion FnDeletePathFiles
  421. #region FnToTWDate
  422. /// <summary>
  423. ///日期轉西元轉民國
  424. /// </summary>
  425. /// <param name="date">todo: describe date parameter on FnToTWDate</param>
  426. public static string FnToTWDate(object date)
  427. {
  428. if (date == null || date.ToString() == @"") return @"";
  429. var dNew = Convert.ToDateTime(date);
  430. var twC = new TaiwanCalendar();
  431. return twC.GetYear(dNew) + dNew.ToString(@"MMdd");
  432. }
  433. //*************************************************
  434. #endregion FnToTWDate
  435. #region GoogleTranslate
  436. public static string GoogleTranslate(string sourceWord, string fromLanguage, string toLanguage)
  437. {
  438. /*
  439. http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=zh-CN|en&q=中国人是好人
  440. json格式如下
  441. {"responseData": {"translatedText":"Chinese people are good people"}, "responseDetails": null, "responseStatus": 200}*/
  442. var serverUrl = @"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair="
  443. + fromLanguage + @"|" + toLanguage + @"&q=" + HttpUtility.UrlEncode(sourceWord);
  444. var request = WebRequest.Create(serverUrl);
  445. var response = request.GetResponse();
  446. using (var streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  447. {
  448. var resJson = streamReader.ReadToEnd();
  449. var textIndex = resJson.IndexOf(@"translatedText") + 17;
  450. var textLen = resJson.IndexOf(@"""", textIndex) - textIndex;
  451. return resJson.Substring(textIndex, textLen);
  452. }
  453. }
  454. #endregion GoogleTranslate
  455. #region WordToPDF
  456. public static bool WordToPDF(string sSourcePath, string sTargetPath)
  457. {
  458. var result = false;
  459. var application = new Microsoft.Office.Interop.Word.Application
  460. {
  461. Visible = false
  462. };
  463. Microsoft.Office.Interop.Word.Document document = null;
  464. try
  465. {
  466. document = application.Documents.Open(sSourcePath);
  467. document.ExportAsFixedFormat(sTargetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
  468. result = true;
  469. }
  470. catch (Exception e)
  471. {
  472. Console.WriteLine(e.Message);
  473. result = false;
  474. }
  475. finally
  476. {
  477. if (document != null)
  478. {
  479. Marshal.FinalReleaseComObject(document);
  480. }
  481. document = null;
  482. application.Quit();
  483. }
  484. return result;
  485. }
  486. #endregion WordToPDF
  487. #region whether Watermark
  488. public static Tuple<bool, string> GetWatermarkInfo(string Status, string TempleteID,string ORGID)
  489. {
  490. var PrintWatermark = false;
  491. var DefaultContent = "Draft Draft Draft Draft Draft ";
  492. switch (Status)
  493. {
  494. case "0":// ╠common.NotAudit⇒未提交審核╣
  495. PrintWatermark = true;
  496. break;
  497. case "1":// ╠common.InAudit⇒提交審核中╣
  498. PrintWatermark = true;
  499. break;
  500. case "2":// ╠common.Audited⇒已審核╣
  501. break;
  502. case "3":// ╠common.NotPass⇒不通過╣
  503. break;
  504. case "4":// ╠common.NotPass⇒已銷帳╣
  505. break;
  506. case "5":// ╠common.HasBeenPost⇒已過帳╣
  507. break;
  508. case "6":// ╠common.HasVoid⇒已作廢╣
  509. break;
  510. case "7":// ╠common.HasReEdit⇒抽單中╣
  511. break;
  512. default:
  513. break;
  514. }
  515. //浮水印內容
  516. if (PrintWatermark)
  517. {
  518. if(TempleteID.EndsWith("TW"))
  519. {
  520. DefaultContent = "單據僅供核對參考";
  521. }
  522. if (ORGID == "SG")
  523. {
  524. DefaultContent = ChineseStringUtility.ToSimplified(DefaultContent);
  525. }
  526. }
  527. else
  528. {
  529. DefaultContent = string.Empty;
  530. }
  531. return new Tuple<bool, string>(PrintWatermark, DefaultContent);
  532. }
  533. #endregion
  534. #region Watermark
  535. public static void WordAddWatermartText(WordprocessingDocument package, string WatermarkContent = "Draft Draft Draft Draft")
  536. {
  537. MainDocumentPart mainDocumentPart1 = package.MainDocumentPart;
  538. if (mainDocumentPart1 != null && mainDocumentPart1.HeaderParts.Any())
  539. {
  540. var HeaderPart1 = mainDocumentPart1.HeaderParts.First();
  541. GenerateHeaderPart1Content(HeaderPart1, WatermarkContent);
  542. string rId = mainDocumentPart1.GetIdOfPart(HeaderPart1);
  543. IEnumerable <SectionProperties > sectPrs = mainDocumentPart1.Document.Body.Elements<SectionProperties>();
  544. foreach (var sectPr in sectPrs)
  545. {
  546. sectPr.RemoveAllChildren<HeaderReference>();
  547. sectPr.PrependChild(new HeaderReference() { Id = rId });
  548. }
  549. }
  550. else
  551. {
  552. HeaderPart headPart1 = mainDocumentPart1.AddNewPart<HeaderPart>();
  553. GenerateHeaderPart1Content(headPart1, WatermarkContent);
  554. string rId = mainDocumentPart1.GetIdOfPart(headPart1);
  555. IEnumerable<SectionProperties> sectPrs = mainDocumentPart1.Document.Body.Elements<SectionProperties>();
  556. foreach (var sectPr in sectPrs)
  557. {
  558. sectPr.RemoveAllChildren<HeaderReference>();
  559. sectPr.PrependChild(new HeaderReference() { Id = rId });
  560. }
  561. }
  562. }
  563. private static void GenerateHeaderPart1Content(HeaderPart headerParts, string p = "Draft Draft Draft Draft")
  564. {
  565. var fill1 = new DocumentFormat.OpenXml.Vml.Fill() { Opacity = ".5" };
  566. Header header1 = new Header();
  567. Paragraph paragraph2 = new Paragraph();
  568. Run run1 = new Run();
  569. var picture1 = new Picture();
  570. var shape1 = new DocumentFormat.OpenXml.Vml.Shape()
  571. {
  572. Id = "PowerPlusWaterMarkObject357476642",
  573. Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin",
  574. OptionalString = "_x0000_s2049",
  575. AllowInCell = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true),
  576. FillColor = "OldLace",
  577. Stroked = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true),
  578. Type = "#_x0000_t136",
  579. StrokeColor = "OldLace",
  580. ForceDash = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true),
  581. };
  582. var path1 = new DocumentFormat.OpenXml.Vml.Path()
  583. {
  584. AllowTextPath = true,
  585. ConnectionPointType = DocumentFormat.OpenXml.Vml.Office.ConnectValues.Custom,
  586. ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800",
  587. ConnectAngles = "270,180,90,0"
  588. };
  589. var textPath = new DocumentFormat.OpenXml.Vml.TextPath
  590. {
  591. Style = "font-family:\"Calibri\";font-size:1pt",
  592. String = p
  593. };
  594. var shape2 = new DocumentFormat.OpenXml.Vml.Shape()
  595. {
  596. Id = "PowerPlusWaterMarkObject357476649",
  597. Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin",
  598. OptionalString = "_x0000_s2049",
  599. AllowInCell = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true),
  600. FillColor = "silver",
  601. Stroked = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true),
  602. Type = "#_x0000_t136"
  603. };
  604. var path2 = new DocumentFormat.OpenXml.Vml.Path()
  605. {
  606. AllowTextPath = true,
  607. ConnectionPointType = DocumentFormat.OpenXml.Vml.Office.ConnectValues.Custom,
  608. ConnectionPoints = "@9,0;@10,10800;@19,21600;@40,10800",
  609. ConnectAngles = "270,180,90,0"
  610. };
  611. shape1.Append(fill1, textPath);
  612. shape1.Filled = DocumentFormat.OpenXml.TrueFalseValue.FromBoolean(true);
  613. picture1.Append(shape1);
  614. run1.Append(picture1);
  615. paragraph2.Append(run1);
  616. //沒有表頭,加入新的表頭就好了
  617. if(headerParts.Header == null)
  618. {
  619. header1.Append(paragraph2);
  620. headerParts.Header = header1;
  621. }
  622. else
  623. {
  624. headerParts.Header.Append(paragraph2);
  625. }
  626. }
  627. #endregion
  628. #region ExcelToPDF
  629. public static bool ExcelToPDF(string sSourcePath, string sTargetPath)
  630. {
  631. var result = false;
  632. var application = new Microsoft.Office.Interop.Excel.Application
  633. {
  634. Visible = false
  635. };
  636. Microsoft.Office.Interop.Excel.Workbook workBook = null;
  637. try
  638. {
  639. var lstrTemp = string.Empty;
  640. object missing = System.Reflection.Missing.Value;
  641. workBook = application.Workbooks.Open(sSourcePath, true, true, missing, missing, missing, true, missing, missing, missing, missing, missing, false, missing, missing);
  642. workBook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, sTargetPath);
  643. result = true;
  644. }
  645. catch (Exception e)
  646. {
  647. Console.WriteLine(e.Message);
  648. result = false;
  649. }
  650. finally
  651. {
  652. if (workBook != null)
  653. {
  654. workBook.Close();
  655. }
  656. application.Quit();
  657. }
  658. return result;
  659. }
  660. #endregion ExcelToPDF
  661. #region Stringfy
  662. public static string Stringfy(JObject jo, string sKey)
  663. {
  664. try
  665. {
  666. if (jo != null)
  667. {
  668. return jo[sKey].ToString();
  669. }
  670. return @"";
  671. }
  672. catch (Exception)
  673. {
  674. return @"";
  675. }
  676. }
  677. #endregion Stringfy
  678. #region Stringfy
  679. /// <summary>
  680. /// </summary>
  681. /// <param name="sAmount"></param>
  682. /// <returns></returns>
  683. public static string MoneyToUpper(string sAmount)
  684. {
  685. string functionReturnValue = null;
  686. var IsNegative = false; // 是否是負數
  687. if (sAmount.Trim().Substring(0, 1) == "-")
  688. {
  689. // 是負數則先轉為正數
  690. sAmount = sAmount.Trim().Remove(0, 1);
  691. IsNegative = true;
  692. }
  693. string strLower = null;
  694. string strUpart = null;
  695. string strUpper = null;
  696. var iTemp = 0;
  697. // 保留兩位小數 123.489→123.49  123.4→123.4
  698. sAmount = Math.Round(double.Parse(sAmount), 2).ToString();
  699. if (sAmount.IndexOf(".") > 0)
  700. {
  701. if (sAmount.IndexOf(".") == sAmount.Length - 2)
  702. {
  703. sAmount = sAmount + "0";
  704. }
  705. }
  706. else
  707. {
  708. sAmount = sAmount + ".00";
  709. }
  710. strLower = sAmount;
  711. iTemp = 1;
  712. strUpper = "";
  713. while (iTemp <= strLower.Length)
  714. {
  715. switch (strLower.Substring(strLower.Length - iTemp, 1))
  716. {
  717. case ".":
  718. strUpart = "元";
  719. break;
  720. case "0":
  721. strUpart = "零";
  722. break;
  723. case "1":
  724. strUpart = "壹";
  725. break;
  726. case "2":
  727. strUpart = "貳";
  728. break;
  729. case "3":
  730. strUpart = "參";
  731. break;
  732. case "4":
  733. strUpart = "肆";
  734. break;
  735. case "5":
  736. strUpart = "伍";
  737. break;
  738. case "6":
  739. strUpart = "陸";
  740. break;
  741. case "7":
  742. strUpart = "柒";
  743. break;
  744. case "8":
  745. strUpart = "捌";
  746. break;
  747. case "9":
  748. strUpart = "玖";
  749. break;
  750. default:
  751. break;
  752. }
  753. switch (iTemp)
  754. {
  755. case 1:
  756. strUpart = strUpart + "分";
  757. break;
  758. case 2:
  759. strUpart = strUpart + "角";
  760. break;
  761. case 3:
  762. strUpart = strUpart + "";
  763. break;
  764. case 4:
  765. strUpart = strUpart + "";
  766. break;
  767. case 5:
  768. strUpart = strUpart + "拾";
  769. break;
  770. case 6:
  771. strUpart = strUpart + "佰";
  772. break;
  773. case 7:
  774. strUpart = strUpart + "仟";
  775. break;
  776. case 8:
  777. strUpart = strUpart + "萬";
  778. break;
  779. case 9:
  780. strUpart = strUpart + "拾";
  781. break;
  782. case 10:
  783. strUpart = strUpart + "佰";
  784. break;
  785. case 11:
  786. strUpart = strUpart + "仟";
  787. break;
  788. case 12:
  789. strUpart = strUpart + "億";
  790. break;
  791. case 13:
  792. strUpart = strUpart + "拾";
  793. break;
  794. case 14:
  795. strUpart = strUpart + "佰";
  796. break;
  797. case 15:
  798. strUpart = strUpart + "仟";
  799. break;
  800. case 16:
  801. strUpart = strUpart + "萬";
  802. break;
  803. default:
  804. strUpart = strUpart + "";
  805. break;
  806. }
  807. strUpper = strUpart + strUpper;
  808. iTemp = iTemp + 1;
  809. }
  810. strUpper = strUpper.Replace("零拾", "零");
  811. strUpper = strUpper.Replace("零佰", "零");
  812. strUpper = strUpper.Replace("零仟", "零");
  813. strUpper = strUpper.Replace("零零零", "零");
  814. strUpper = strUpper.Replace("零零", "零");
  815. strUpper = strUpper.Replace("零角零分", "");
  816. strUpper = strUpper.Replace("零分", "");
  817. strUpper = strUpper.Replace("零角", "零");
  818. strUpper = strUpper.Replace("零億零萬零元", "億元");
  819. strUpper = strUpper.Replace("億零萬零元", "億元");
  820. strUpper = strUpper.Replace("零億零萬", "億");
  821. strUpper = strUpper.Replace("零萬零元", "萬元");
  822. strUpper = strUpper.Replace("零億", "億");
  823. strUpper = strUpper.Replace("零萬", "萬");
  824. strUpper = strUpper.Replace("零元", "元");
  825. strUpper = strUpper.Replace("零零", "零");
  826. // 對壹元以下的金額的處理
  827. if (strUpper.Substring(0, 1) == "元")
  828. {
  829. strUpper = strUpper.Substring(1, strUpper.Length - 1);
  830. }
  831. if (strUpper != "" && strUpper.Substring(0, 1) == "零")
  832. {
  833. strUpper = strUpper.Substring(1, strUpper.Length - 1);
  834. }
  835. if (strUpper != "" && strUpper.Substring(0, 1) == "角")
  836. {
  837. strUpper = strUpper.Substring(1, strUpper.Length - 1);
  838. }
  839. if (strUpper != "" && strUpper.Substring(0, 1) == "分")
  840. {
  841. strUpper = strUpper.Substring(1, strUpper.Length - 1);
  842. }
  843. if ((strUpper != "" && strUpper.Substring(0, 1) == "") || strUpper == "")
  844. {
  845. strUpper = "零元";
  846. }
  847. functionReturnValue = string.Join(" ", Regex.Split(strUpper, "(?<=\\G.{1})(?!$)"));
  848. return IsNegative ? "負" + functionReturnValue : functionReturnValue;
  849. }
  850. #endregion Stringfy
  851. /// <summary>
  852. /// 截取指定字節長度的字符串
  853. /// </summary>
  854. /// <param name="sStr">todo: describe sStr parameter on CutByteString</param>
  855. /// <param name="iLen">todo: describe iLen parameter on CutByteString</param>
  856. /// <returns></returns>
  857. public static string CutByteString(string sStr, int iLen)
  858. {
  859. var result = string.Empty;// 最終返回的結果
  860. if (string.IsNullOrEmpty(sStr)) { return result; }
  861. var byteLen = Encoding.Default.GetByteCount(sStr);// 單字節字符長度
  862. var charLen = sStr.Length;// 把字符平等對待時的字符串長度
  863. var byteCount = 0;// 記錄讀取進度
  864. var pos = 0;// 記錄截取位置
  865. if (byteLen > iLen)
  866. {
  867. for (int i = 0; i < charLen; i++)
  868. {
  869. if (Convert.ToInt32(sStr.ToCharArray()[i]) > 255)// 按中文字符計算加2
  870. { byteCount += 2; }
  871. else// 按英文字符計算加1
  872. { byteCount += 1; }
  873. if (byteCount > iLen)// 超出時只記下上一個有效位置
  874. {
  875. pos = i;
  876. break;
  877. }
  878. else if (byteCount == iLen)// 記下當前位置
  879. {
  880. pos = i + 1;
  881. break;
  882. }
  883. }
  884. if (pos >= 0)
  885. { result = sStr.Substring(0, pos); }
  886. }
  887. else
  888. { result = sStr; }
  889. return result;
  890. }
  891. public static string EncodeEscapeChar(string OriStr)
  892. {
  893. if (string.IsNullOrWhiteSpace(OriStr))
  894. return "";
  895. return OriStr.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
  896. }
  897. }
  898. }